From ef91ca18a37d80499232252050e67678f99bc512 Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 13:31:45 +0100 Subject: [PATCH 1/6] Fixed the Java arrays-related code --- java/11_find_arrays.ipynb | 88 +++++++++++---------------------------- 1 file changed, 24 insertions(+), 64 deletions(-) diff --git a/java/11_find_arrays.ipynb b/java/11_find_arrays.ipynb index 72ddeaa..c85de0f 100644 --- a/java/11_find_arrays.ipynb +++ b/java/11_find_arrays.ipynb @@ -22,7 +22,7 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code\n" ] }, { @@ -36,64 +36,19 @@ }, "outputs": [], "source": [ + "// Import the MongoDB Driver using Maven\n", "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", " \n", "import com.mongodb.client.*;\n", "import org.bson.Document;\n", "import org.bson.json.JsonWriterSettings;\n", "import java.util.ArrayList;\n", - "import java.util.List;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" - ] - }, - { - "cell_type": "markdown", - "id": "13926b8c", - "metadata": {}, - "source": [ - "## Define DB and collection" - ] - }, - { - "cell_type": "markdown", - "id": "0453e747", - "metadata": {}, - "source": [ - "Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af4eccbc", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ + "import java.util.List;\n", + "\n", + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", "MongoClient mongoClient = null;\n", "try {\n", " // connect to MongoDB\n", @@ -125,11 +80,16 @@ }, "outputs": [], "source": [ - "Bson poetryBooks = Filters.eq(\"genre\", \"Poetry\");\n", - "Document aBook = books.find(poetryBooks);\n", + "import static com.mongodb.client.model.Filters.*;\n", + "import org.bson.conversions.Bson;\n", + "\n", + "Bson poetryBooks = eq(\"genres\", \"Poetry\");\n", + "FindIterable cursor = books.find(poetryBooks);\n", "\n", - "if (aBook != null) {\n", - " System.out.println(\"Book: \" + aBook.toJson());\n", + "if (cursor != null) {\n", + " for(Document b: cursor) {\n", + " System.out.println(\"Book: \" + b.toJson());\n", + " }\n", "} else {\n", " System.out.println(\"Empty collection\");\n", "}" @@ -157,8 +117,8 @@ "import static com.mongodb.client.model.Filters.*;\n", "import org.bson.conversions.Bson;\n", "\n", - "Bson poetryAndFictionBooks = Filters.all(\"genre.name\", \"Poetry\", \"Fiction\")\n", - "FindIterable cursor = books.find(booksAfpoetryAndFictionBookster2008);\n", + "Bson familyLifeAndFictionBooks = all(\"genres\", \"Family Life\", \"Fiction\");\n", + "FindIterable cursor = books.find(familyLifeAndFictionBooks);\n", "\n", "if (cursor != null) {\n", " for(Document b: cursor) {\n", @@ -191,8 +151,8 @@ "import static com.mongodb.client.model.Filters.*;\n", "import org.bson.conversions.Bson;\n", "\n", - "Bson poetryAndFictionBooks = Filters.in(\"genre.name\", \"Poetry\", \"Fiction\")\n", - "FindIterable cursor = books.find(booksAfpoetryAndFictionBookster2008);\n", + "Bson familyLifeOrFictionBooks = in(\"genres\", \"Family Life\", \"Fiction\");\n", + "FindIterable cursor = books.find(familyLifeOrFictionBooks);\n", "\n", "if (cursor != null) {\n", " for(Document b: cursor) {\n", @@ -208,7 +168,7 @@ "id": "1e62db28", "metadata": {}, "source": [ - "## Don't make this mistake!", + "## Don't make this mistake!\n", "\n", "The query below will try to find books that have exactly two genres (Poetry and Fiction) in the designated order. The query looks for an exact match of the array. Usually we want to search inside the array." ] @@ -227,7 +187,7 @@ "import static com.mongodb.client.model.Filters.*;\n", "import org.bson.conversions.Bson;\n", "\n", - "Bson poetryAndFictionBooks = Filters.eq(\"genre.name\", new String[] { \"Poetry\", \"Fiction\" }))\n", + "Bson poetryAndFictionBooks = eq(\"genres\", Arrays.asList(\"Poetry\", \"Fiction\"));\n", "FindIterable cursor = books.find(poetryAndFictionBooks);\n", "\n", "if (cursor != null) {\n", @@ -252,7 +212,7 @@ "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, From 45032c3f9989cd629aec8e41e40ed4c1c3d07bad Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 13:32:11 +0100 Subject: [PATCH 2/6] Added printing all collections at the beginning --- java/00_open_mongodb.ipynb | 3 +- java/01_connect_database.ipynb | 53 +++++++++++++++++++++++++++------- 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/java/00_open_mongodb.ipynb b/java/00_open_mongodb.ipynb index 1afa73d..2f27bcf 100644 --- a/java/00_open_mongodb.ipynb +++ b/java/00_open_mongodb.ipynb @@ -24,8 +24,7 @@ "- admin\n", "- config\n", "- local\n", - "- library -> __we're going to work with this one__\n", - "- library_with_embedding -> same data, but books have vector embedding for vector search" + "- library -> __we're going to work with this one__" ] }, { diff --git a/java/01_connect_database.ipynb b/java/01_connect_database.ipynb index 40e8a0b..5fbeb2e 100644 --- a/java/01_connect_database.ipynb +++ b/java/01_connect_database.ipynb @@ -49,7 +49,11 @@ "cell_type": "code", "execution_count": null, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", @@ -75,7 +79,11 @@ "cell_type": "code", "execution_count": null, "id": "urban-boston", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" @@ -88,14 +96,18 @@ "source": [ "## Ping the Database server\n", "\n", - "The ping() database command fetches information about the state of the MongoDB database." + "The `ping()` database command fetches information about the state of the MongoDB database." ] }, { "cell_type": "code", "execution_count": null, "id": "textile-spokesman", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "MongoClient mongoClient = null;\n", @@ -125,7 +137,11 @@ "cell_type": "code", "execution_count": null, "id": "00dd063a", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "try {\n", @@ -142,7 +158,7 @@ "id": "amazing-webcam", "metadata": {}, "source": [ - "## List all databases in the cluster\n", + "## Get a list of all databases and collections\n", "\n", "We'll get a list of all the databases in my cluster using `listDatabases()` and then we'll print them." ] @@ -152,20 +168,35 @@ "execution_count": null, "id": "annoying-tattoo", "metadata": { - "scrolled": true + "scrolled": true, + "vscode": { + "languageId": "java" + } }, "outputs": [], "source": [ "System.out.println(\"=> Print list of databases\");\n", "List databases = mongoClient.listDatabases().into(new ArrayList<>());\n", - "databases.forEach(db -> System.out.println(db.toJson()));" + "databases.forEach(dbDoc -> {\n", + " String dbName = dbDoc.getString(\"name\");\n", + " MongoDatabase db = mongoClient.getDatabase(dbName);\n", + "\n", + " db.listCollectionNames().forEach(collectionName -> \n", + " System.out.println(dbName + \".\" + collectionName)\n", + " );\n", + " }\n", + ");" ] }, { "cell_type": "code", "execution_count": null, "id": "19f3150c", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [] } @@ -180,9 +211,9 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "java", + "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, From 751a8484d4ccb12d68f2b67b3c4a71c222fce20a Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 13:33:04 +0100 Subject: [PATCH 3/6] Improved find instructions --- java/10_find.ipynb | 18 +++++++++--------- javascript/01_connect_database.ipynb | 8 ++++++-- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/java/10_find.ipynb b/java/10_find.ipynb index e1c187a..35842b5 100644 --- a/java/10_find.ipynb +++ b/java/10_find.ipynb @@ -175,7 +175,7 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "## Exercise: find all the books that have less than 50 pages and project only the title and pages" + "## Find all the books that have less than 50 pages and project only the title and pages" ] }, { @@ -270,7 +270,7 @@ }, "outputs": [], "source": [ - "// type in your code here, you'll need to adapt the code a bit\n" + "// type in your code here\n" ] }, { @@ -278,7 +278,7 @@ "id": "627c4fb7", "metadata": {}, "source": [ - "## Find all books with more than 300 pages.\n", + "### Find all books longer than 300 pages.\n", "\n", "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/WHERE#2-find-all-books-with-more-than-300-pages)" ] @@ -289,12 +289,12 @@ "id": "fd8a8143", "metadata": { "vscode": { - "languageId": "markdown" + "languageId": "java" } }, "outputs": [], "source": [ - "// type in your code here, you'll need to adapt the code a bit\n" + "// type in your code here\n" ] }, { @@ -302,7 +302,7 @@ "id": "601d0b12", "metadata": {}, "source": [ - "## Find books in the Science genre that are more than 300 pages long.\n", + "### Find books in the Science genre that are longer than 300 pages long.\n", "\n", "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/WHERE#3-find-books-in-the-science-genre-that-are-more-than-300-pages-long)" ] @@ -313,12 +313,12 @@ "id": "1a94638b", "metadata": { "vscode": { - "languageId": "markdown" + "languageId": "java" } }, "outputs": [], "source": [ - "// type in your code here, you'll need to adapt the code a bit\n" + "// type in your code here\n" ] } ], @@ -334,7 +334,7 @@ "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, diff --git a/javascript/01_connect_database.ipynb b/javascript/01_connect_database.ipynb index c1c258e..cc293ec 100644 --- a/javascript/01_connect_database.ipynb +++ b/javascript/01_connect_database.ipynb @@ -87,7 +87,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Send a ping command" + "## Send a ping command\n", + "\n", + "The `ping()` database command fetches information about the state of the MongoDB database." ] }, { @@ -121,7 +123,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Get a list of all databases and collections" + "## Get a list of all databases and collections\n", + "\n", + "We'll get a list of all the databases in my cluster using `listDatabases()` and then we'll print them." ] }, { From 9a81f37f46398963587b8f900cb965859b86f3c5 Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 13:52:12 +0100 Subject: [PATCH 4/6] Fixed insert / delete and organized startup code --- java/30_insert.ipynb | 114 +++++++++++++++++++++++++++---------------- java/40_delete.ipynb | 100 ++++++++++++++++++------------------- 2 files changed, 122 insertions(+), 92 deletions(-) diff --git a/java/30_insert.ipynb b/java/30_insert.ipynb index 709cb70..96e67e7 100644 --- a/java/30_insert.ipynb +++ b/java/30_insert.ipynb @@ -22,58 +22,33 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code" ] }, { "cell_type": "code", "execution_count": null, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ + "// Import the MongoDB Driver using Maven\n", "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", " \n", "import com.mongodb.client.*;\n", "import org.bson.Document;\n", "import org.bson.json.JsonWriterSettings;\n", "import java.util.ArrayList;\n", - "import java.util.List;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": {}, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" - ] - }, - { - "cell_type": "markdown", - "id": "13926b8c", - "metadata": {}, - "source": [ - "## CRUD: Insert" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af4eccbc", - "metadata": {}, - "outputs": [], - "source": [ + "import java.util.List;\n", + "\n", + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", "MongoClient mongoClient = null;\n", "try {\n", " // connect to MongoDB\n", @@ -86,6 +61,14 @@ "MongoCollection books = library.getCollection(\"books\");" ] }, + { + "cell_type": "markdown", + "id": "13926b8c", + "metadata": {}, + "source": [ + "## CRUD: Insert" + ] + }, { "cell_type": "markdown", "id": "handled-symbol", @@ -98,7 +81,11 @@ "cell_type": "code", "execution_count": null, "id": "african-maple", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "Document elQuijote = new Document();\n", @@ -119,7 +106,11 @@ "cell_type": "code", "execution_count": null, "id": "35e0771f", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "Document bookFrom1500 = new Document(\"year\", 1500);\n", @@ -147,7 +138,11 @@ "cell_type": "code", "execution_count": null, "id": "polar-pride", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import org.bson.types.ObjectId;\n", @@ -164,6 +159,39 @@ " System.out.println(\"Empty collection\");\n", "}" ] + }, + { + "cell_type": "markdown", + "id": "490cd5f6", + "metadata": {}, + "source": [ + "## Challenges" + ] + }, + { + "cell_type": "markdown", + "id": "cb8e4e85", + "metadata": {}, + "source": [ + "### Insert 4 more reviews for bookId \"0786222727\".\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/INSERT-DELETE#-1-insert-4-more-reviews-for-bookid-0786222727)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "65818c9d", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "// type your code here\n", + " " + ] } ], "metadata": { @@ -176,9 +204,9 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "java", + "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, diff --git a/java/40_delete.ipynb b/java/40_delete.ipynb index 3532c93..ff34949 100644 --- a/java/40_delete.ipynb +++ b/java/40_delete.ipynb @@ -22,7 +22,7 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code" ] }, { @@ -36,56 +36,19 @@ }, "outputs": [], "source": [ + "// Import the MongoDB Driver using Maven\n", "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", " \n", "import com.mongodb.client.*;\n", "import org.bson.Document;\n", "import org.bson.json.JsonWriterSettings;\n", "import java.util.ArrayList;\n", - "import java.util.List;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" - ] - }, - { - "cell_type": "markdown", - "id": "13926b8c", - "metadata": {}, - "source": [ - "## Define DB and collection" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af4eccbc", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ + "import java.util.List;\n", + "\n", + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", "MongoClient mongoClient = null;\n", "try {\n", " // connect to MongoDB\n", @@ -103,9 +66,9 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "### Insert one book\n", + "## Insert one book\n", "\n", - "We want to make sure this book is in the collection, so we can delete it" + "We want to make sure this book is in the collection, so we can later delete it." ] }, { @@ -184,7 +147,6 @@ "source": [ "import com.mongodb.client.result.DeleteResult;\n", "\n", - "\n", "Document bookFrom1500 = new Document(\"year\", 1500);\n", "\n", "DeleteResult deleteResult = books.deleteOne(new Document(\"_id\", \"platero\"));\n", @@ -193,6 +155,46 @@ "long deletedCount = deleteResult.getDeletedCount();\n", "System.out.println(\"Deleted \" + deletedCount + \" document(s).\");" ] + }, + { + "cell_type": "markdown", + "id": "36142464", + "metadata": {}, + "source": [ + "## Challenge" + ] + }, + { + "cell_type": "markdown", + "id": "cb9af92a", + "metadata": {}, + "source": [ + "### Delete all the reviews for bookId \"0786222727\" through a single command.\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/INSERT-DELETE#-2-delete-all-the-reviews-for-bookid-0786222727-through-a-single-command)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cffe0b1a", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "import static com.mongodb.client.model.Filters.*;\n", + "import org.bson.conversions.Bson;\n", + "\n", + "MongoCollection reviews = library.getCollection(\"reviews\");\n", + "\n", + "Bson filter = eq(\"bookId\", \"0786222727\");\n", + "\n", + "DeleteResult result = reviews.deleteMany(filter);\n", + "System.out.println(result.getDeletedCount() + \" reviews deleted.\");" + ] } ], "metadata": { @@ -207,7 +209,7 @@ "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, From f8cb20673f019bf8e3a1d00497c1bcce6aa8747a Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 14:09:35 +0100 Subject: [PATCH 5/6] Fixed insert and update --- java/50_update.ipynb | 282 ++++++++++++++++++++++++++++++++++-------- java/60_indexes.ipynb | 99 ++++----------- 2 files changed, 254 insertions(+), 127 deletions(-) diff --git a/java/50_update.ipynb b/java/50_update.ipynb index 5706c42..2390ad0 100644 --- a/java/50_update.ipynb +++ b/java/50_update.ipynb @@ -22,58 +22,33 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ + "// Import the MongoDB Driver using Maven\n", "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", " \n", "import com.mongodb.client.*;\n", "import org.bson.Document;\n", "import org.bson.json.JsonWriterSettings;\n", "import java.util.ArrayList;\n", - "import java.util.List;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": {}, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" - ] - }, - { - "cell_type": "markdown", - "id": "13926b8c", - "metadata": {}, - "source": [ - "## Define DB and collection" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af4eccbc", - "metadata": {}, - "outputs": [], - "source": [ + "import java.util.List;\n", + "\n", + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", "MongoClient mongoClient = null;\n", "try {\n", " // connect to MongoDB\n", @@ -91,15 +66,34 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "### Insert one book" + "## Insert one book" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "id": "african-maple", - "metadata": {}, - "outputs": [], + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "ename": "EvalException", + "evalue": "Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: library.books index: _id_ dup key: { _id: \"quijote\" }', details={}}.", + "output_type": "error", + "traceback": [ + "\u001b[1m\u001b[31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1m\u001b[31mcom.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: library.books index: _id_ dup key: { _id: \"quijote\" }', details={}}.\u001b[0m", + "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1091)\u001b[0m", + "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:477)\u001b[0m", + "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:460)\u001b[0m", + "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:454)\u001b[0m", + "\u001b[1m\u001b[31m\tat .(#47:1)\u001b[0m" + ] + } + ], "source": [ "Document elQuijote = new Document();\n", "elQuijote\n", @@ -120,10 +114,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "id": "polar-pride", - "metadata": {}, - "outputs": [], + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Book: {\"_id\": \"quijote\", \"title\": \"El Quijote\", \"year\": 1501, \"genres\": [\"Chivalry\"], \"lastUpdated\": {\"$timestamp\": {\"t\": 1762865826, \"i\": 2}}, \"newField\": 99}\n" + ] + } + ], "source": [ "import org.bson.types.ObjectId;\n", "\n", @@ -162,10 +168,23 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "id": "91c58788", - "metadata": {}, - "outputs": [], + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Modified document count: 1\n", + "Upserted id: null\n" + ] + } + ], "source": [ "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", @@ -208,15 +227,170 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "8a6156ed", - "metadata": {}, - "outputs": [], + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Book: {\"_id\": \"quijote\", \"title\": \"El Quijote\", \"year\": 1501, \"genres\": [\"Chivalry\"], \"lastUpdated\": {\"$timestamp\": {\"t\": 1762866146, \"i\": 2}}, \"newField\": 99}\n" + ] + } + ], "source": [ "Document aBook = books.find(new Document(\"_id\", \"quijote\")).first();\n", "\n", "System.out.println(\"Book: \" + aBook.toJson());" ] + }, + { + "cell_type": "markdown", + "id": "398d39bb", + "metadata": {}, + "source": [ + "### Upsert" + ] + }, + { + "cell_type": "markdown", + "id": "ba85cf52", + "metadata": {}, + "source": [ + "### Delete the book, so it's not there and can't be updated" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "ac704a84", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Deleted 1 document(s).\n" + ] + } + ], + "source": [ + "import com.mongodb.client.result.DeleteResult;\n", + "\n", + "DeleteResult deleteResult = books.deleteOne(new Document(\"_id\", \"quijote\"));\n", + "\n", + "// Check the number of deleted documents\n", + "long deletedCount = deleteResult.getDeletedCount();\n", + "System.out.println(\"Deleted \" + deletedCount + \" document(s).\");" + ] + }, + { + "cell_type": "markdown", + "id": "e5ddfd06", + "metadata": {}, + "source": [ + "### Upsert: we try to update it but will get inserted instead" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "bd6931b0", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Modified document count: 0\n", + "Upserted id: BsonString{value='quijote'}\n" + ] + } + ], + "source": [ + "import org.bson.Document;\n", + "import org.bson.conversions.Bson;\n", + "import com.mongodb.MongoException;\n", + "import com.mongodb.client.model.UpdateOptions;\n", + "import com.mongodb.client.model.Updates;\n", + "import com.mongodb.client.result.UpdateResult;\n", + "\n", + "Document query = new Document(\"_id\", \"quijote\");\n", + "\n", + "// Creates instructions to update the values of three document fields\n", + "Bson updates = Updates.combine(\n", + " Updates.set(\"newField\", 99),\n", + " Updates.addToSet(\"genres\", \"Chivalry\"),\n", + " Updates.currentTimestamp(\"lastUpdated\"));\n", + "\n", + "// Instructs the driver to insert a new document if none match the query\n", + "UpdateOptions options = new UpdateOptions().upsert(true);\n", + "\n", + "try {\n", + " // Updates the first document that has a \"title\" value of \"Cool Runnings 2\"\n", + " UpdateResult result = books.updateOne(query, updates, options);\n", + " // Prints the number of updated documents and the upserted document ID, if an upsert was performed\n", + " System.out.println(\"Modified document count: \" + result.getModifiedCount());\n", + " System.out.println(\"Upserted id: \" + result.getUpsertedId());\n", + "\n", + "// Prints a message if any exceptions occur during the operation\n", + "} catch (MongoException me) {\n", + " System.err.println(\"Unable to update due to an error: \" + me);\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "b8bfa616", + "metadata": {}, + "source": [ + "## Challenge" + ] + }, + { + "cell_type": "markdown", + "id": "fe70e1e8", + "metadata": {}, + "source": [ + "### Update the pages of the book \"Treasure of the Sun\" to 449.\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/UPDATE#-1-update-the-pages-of-the-book-treasure-of-the-sun-to-449)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5393f03c", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 document(s) updated.\n" + ] + } + ], + "source": [ + "// type your code here\n" + ] } ], "metadata": { @@ -229,9 +403,9 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "java", + "name": "Java", "pygments_lexer": "java", - "version": "21.0.7+6-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, diff --git a/java/60_indexes.ipynb b/java/60_indexes.ipynb index 5d65780..4aaaa69 100644 --- a/java/60_indexes.ipynb +++ b/java/60_indexes.ipynb @@ -21,18 +21,14 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code" ] }, { "cell_type": "code", "execution_count": null, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", @@ -42,29 +38,22 @@ "import org.bson.json.JsonWriterSettings;\n", "import java.util.ArrayList;\n", "import java.util.List;\n", - "import com.mongodb.MongoCommandException;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" + "import com.mongodb.MongoCommandException;\n", + "\n", + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", + "MongoClient mongoClient = null;\n", + "try {\n", + " // connect to MongoDB\n", + " mongoClient = MongoClients.create(connectionString); \n", + "} catch (Exception e) {\n", + " System.out.println(e);\n", + "}\n", + "\n", + "MongoDatabase library = mongoClient.getDatabase(\"library\");\n", + "MongoCollection books = library.getCollection(\"books\");" ] }, { @@ -79,32 +68,16 @@ "cell_type": "code", "execution_count": null, "id": "af4eccbc", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ - "MongoClient mongoClient = null;\n", - "try {\n", - " // connect to MongoDB\n", - " mongoClient = MongoClients.create(connectionString); \n", - "} catch (Exception e) {\n", - " System.out.println(e);\n", - "}\n", - "\n", - "MongoDatabase library = mongoClient.getDatabase(\"library\");\n", - "MongoCollection books = library.getCollection(\"books\");\n", - "\n", - "\n", "try {\n", " // drop the index\n", " books.dropIndex(\"pages_1_year_1\");\n", " System.out.println(\"Index dropped!\");\n", "} catch (MongoCommandException e) {\n", " System.out.println(e);\n", - "}\n" + "}" ] }, { @@ -119,11 +92,7 @@ "cell_type": "code", "execution_count": null, "id": "proof-syria", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -158,11 +127,7 @@ "cell_type": "code", "execution_count": null, "id": "4be194a3", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -192,11 +157,7 @@ "cell_type": "code", "execution_count": null, "id": "10d0887f", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "import com.mongodb.client.model.IndexOptions;\n", @@ -224,11 +185,7 @@ "cell_type": "code", "execution_count": null, "id": "90ef3e33", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -263,11 +220,7 @@ "cell_type": "code", "execution_count": null, "id": "443693dd", - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "metadata": {}, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -296,7 +249,7 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "Java", + "name": "java", "pygments_lexer": "java", "version": "21.0.7+6-LTS" } From 20e3e20c358e35580d73d83560667b0eac2eba6d Mon Sep 17 00:00:00 2001 From: Diego Freniche Date: Tue, 11 Nov 2025 17:50:09 +0100 Subject: [PATCH 6/6] Consolidated startup code in the 1st aggregation pipeline file --- java/100_aggregation_pipeline_match.ipynb | 114 +++++++++++----------- java/50_update.ipynb | 93 +++--------------- java/60_indexes.ipynb | 46 +++++++-- 3 files changed, 110 insertions(+), 143 deletions(-) diff --git a/java/100_aggregation_pipeline_match.ipynb b/java/100_aggregation_pipeline_match.ipynb index 2da1dde..fb4296f 100644 --- a/java/100_aggregation_pipeline_match.ipynb +++ b/java/100_aggregation_pipeline_match.ipynb @@ -44,54 +44,14 @@ "import com.mongodb.client.MongoCollection;\n", "import com.mongodb.client.MongoDatabase;\n", "import com.mongodb.client.model.Accumulators;\n", - "import com.mongodb.client.model.Aggregates;\n", - "import com.mongodb.client.model.Filters;\n", "import org.bson.Document;\n", + "import org.bson.conversions.Bson;\n", + "import java.util.Arrays;\n", "\n", - "import java.util.Arrays;" - ] - }, - { - "cell_type": "markdown", - "id": "advisory-christmas", - "metadata": {}, - "source": [ - "## Set your connection String below" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "urban-boston", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";" - ] - }, - { - "cell_type": "markdown", - "id": "13926b8c", - "metadata": {}, - "source": [ - "## $match" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af4eccbc", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ + "// Set your connection String\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "// Define our database and collection. We'll use the `library` variable that points to our Database and `books` that points to the collection we're using.\n", "MongoClient mongoClient = null;\n", "try {\n", " // connect to MongoDB\n", @@ -109,7 +69,9 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "### $match" + "## $match\n", + "\n", + "We'll get all book written after 2010" ] }, { @@ -123,11 +85,16 @@ }, "outputs": [], "source": [ - "AggregateIterable result = books.aggregate(Arrays.asList(\n", - " Aggregates.match(Filters.and(\n", - " Filters.eq(\"year\", 2010)\n", + "import static com.mongodb.client.model.Aggregates.*;\n", + "import static com.mongodb.client.model.Filters.*;\n", + "\n", + "List booksFrom2010 = Arrays.asList(\n", + " match(and(\n", + " gte(\"year\", 2010)\n", " ))\n", - "));\n", + ");\n", + "\n", + "AggregateIterable result = books.aggregate(booksFrom2010);\n", "\n", "// Iterate through the results\n", "for (Document doc : result) {\n", @@ -140,7 +107,9 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "### $limit" + "### $limit\n", + "\n", + "Now we want to limit just to 10 books" ] }, { @@ -153,7 +122,24 @@ } }, "outputs": [], - "source": [] + "source": [ + "import static com.mongodb.client.model.Aggregates.*;\n", + "import static com.mongodb.client.model.Filters.*;\n", + "\n", + "List tenBooksFrom2010 = Arrays.asList(\n", + " match(and(\n", + " gte(\"year\", 2010)\n", + " )),\n", + " limit(10)\n", + ");\n", + "\n", + "AggregateIterable result = books.aggregate(tenBooksFrom2010);\n", + "\n", + "// Iterate through the results\n", + "for (Document doc : result) {\n", + " System.out.println(\"book: \" + doc.toJson());\n", + "}" + ] }, { "cell_type": "markdown", @@ -173,7 +159,25 @@ } }, "outputs": [], - "source": [] + "source": [ + "import static com.mongodb.client.model.Aggregates.*;\n", + "import static com.mongodb.client.model.Filters.*;\n", + "\n", + "List tenBooksFrom2010 = Arrays.asList(\n", + " match(and(\n", + " gte(\"year\", 2010)\n", + " )),\n", + " limit(10),\n", + " sort(new Document(\"year\", 1))\n", + ");\n", + "\n", + "AggregateIterable result = books.aggregate(tenBooksFrom2010);\n", + "\n", + "// Iterate through the results\n", + "for (Document doc : result) {\n", + " System.out.println(\"book: \" + doc.toJson());\n", + "}" + ] } ], "metadata": { @@ -188,7 +192,7 @@ "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", - "version": "21.0.5+11-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4, diff --git a/java/50_update.ipynb b/java/50_update.ipynb index 2390ad0..f6b99f0 100644 --- a/java/50_update.ipynb +++ b/java/50_update.ipynb @@ -27,7 +27,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": null, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", "metadata": { "vscode": { @@ -71,29 +71,14 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": null, "id": "african-maple", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "ename": "EvalException", - "evalue": "Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: library.books index: _id_ dup key: { _id: \"quijote\" }', details={}}.", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1m\u001b[31mcom.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: library.books index: _id_ dup key: { _id: \"quijote\" }', details={}}.\u001b[0m", - "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1091)\u001b[0m", - "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:477)\u001b[0m", - "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:460)\u001b[0m", - "\u001b[1m\u001b[31m\tat com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:454)\u001b[0m", - "\u001b[1m\u001b[31m\tat .(#47:1)\u001b[0m" - ] - } - ], + "outputs": [], "source": [ "Document elQuijote = new Document();\n", "elQuijote\n", @@ -114,22 +99,14 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": null, "id": "polar-pride", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Book: {\"_id\": \"quijote\", \"title\": \"El Quijote\", \"year\": 1501, \"genres\": [\"Chivalry\"], \"lastUpdated\": {\"$timestamp\": {\"t\": 1762865826, \"i\": 2}}, \"newField\": 99}\n" - ] - } - ], + "outputs": [], "source": [ "import org.bson.types.ObjectId;\n", "\n", @@ -168,23 +145,14 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": null, "id": "91c58788", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Modified document count: 1\n", - "Upserted id: null\n" - ] - } - ], + "outputs": [], "source": [ "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", @@ -227,22 +195,14 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": null, "id": "8a6156ed", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Book: {\"_id\": \"quijote\", \"title\": \"El Quijote\", \"year\": 1501, \"genres\": [\"Chivalry\"], \"lastUpdated\": {\"$timestamp\": {\"t\": 1762866146, \"i\": 2}}, \"newField\": 99}\n" - ] - } - ], + "outputs": [], "source": [ "Document aBook = books.find(new Document(\"_id\", \"quijote\")).first();\n", "\n", @@ -267,22 +227,14 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": null, "id": "ac704a84", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Deleted 1 document(s).\n" - ] - } - ], + "outputs": [], "source": [ "import com.mongodb.client.result.DeleteResult;\n", "\n", @@ -303,23 +255,14 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": null, "id": "bd6931b0", "metadata": { "vscode": { "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Modified document count: 0\n", - "Upserted id: BsonString{value='quijote'}\n" - ] - } - ], + "outputs": [], "source": [ "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", @@ -379,15 +322,7 @@ "languageId": "java" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 document(s) updated.\n" - ] - } - ], + "outputs": [], "source": [ "// type your code here\n" ] diff --git a/java/60_indexes.ipynb b/java/60_indexes.ipynb index 4aaaa69..f5630e6 100644 --- a/java/60_indexes.ipynb +++ b/java/60_indexes.ipynb @@ -28,7 +28,11 @@ "cell_type": "code", "execution_count": null, "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", @@ -68,7 +72,11 @@ "cell_type": "code", "execution_count": null, "id": "af4eccbc", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "try {\n", @@ -92,7 +100,11 @@ "cell_type": "code", "execution_count": null, "id": "proof-syria", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -127,7 +139,11 @@ "cell_type": "code", "execution_count": null, "id": "4be194a3", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -157,7 +173,11 @@ "cell_type": "code", "execution_count": null, "id": "10d0887f", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import com.mongodb.client.model.IndexOptions;\n", @@ -185,7 +205,11 @@ "cell_type": "code", "execution_count": null, "id": "90ef3e33", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -220,7 +244,11 @@ "cell_type": "code", "execution_count": null, "id": "443693dd", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import static com.mongodb.client.model.Filters.*;\n", @@ -249,9 +277,9 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "java", + "name": "Java", "pygments_lexer": "java", - "version": "21.0.7+6-LTS" + "version": "21.0.8+9-LTS" } }, "nbformat": 4,