From d947f5b23cb312ba308dcdc32027709551807e3b Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 19:08:22 -0300 Subject: [PATCH 1/9] Updating mongodb and slj4 version --- java/11_find_arrays.ipynb | 3 ++- java/30_insert.ipynb | 3 ++- java/40_delete.ipynb | 3 ++- java/50_update.ipynb | 3 ++- java/60_indexes.ipynb | 5 +++-- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/java/11_find_arrays.ipynb b/java/11_find_arrays.ipynb index 8fc2db6..b82c607 100644 --- a/java/11_find_arrays.ipynb +++ b/java/11_find_arrays.ipynb @@ -37,7 +37,8 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", " \n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", diff --git a/java/30_insert.ipynb b/java/30_insert.ipynb index c808e77..08c5af3 100644 --- a/java/30_insert.ipynb +++ b/java/30_insert.ipynb @@ -37,7 +37,8 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", " \n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", diff --git a/java/40_delete.ipynb b/java/40_delete.ipynb index 3beecb5..f4b9454 100644 --- a/java/40_delete.ipynb +++ b/java/40_delete.ipynb @@ -37,7 +37,8 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", " \n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", diff --git a/java/50_update.ipynb b/java/50_update.ipynb index e038f4a..df14164 100644 --- a/java/50_update.ipynb +++ b/java/50_update.ipynb @@ -37,7 +37,8 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", " \n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", diff --git a/java/60_indexes.ipynb b/java/60_indexes.ipynb index 16a8036..750711e 100644 --- a/java/60_indexes.ipynb +++ b/java/60_indexes.ipynb @@ -36,8 +36,9 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", - " \n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", + "\n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", "import com.mongodb.client.MongoDatabase;\n", From 890bd841dd38904d7c8663b3c9cd40fa27e5d473 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 19:08:43 -0300 Subject: [PATCH 2/9] renaming find file --- java/10_find.ipynb | 332 ---------------------------- java/10_find_project.ipynb | 437 +++++++++++++++++++++++++++++++++++++ 2 files changed, 437 insertions(+), 332 deletions(-) delete mode 100644 java/10_find.ipynb create mode 100644 java/10_find_project.ipynb diff --git a/java/10_find.ipynb b/java/10_find.ipynb deleted file mode 100644 index ac6d8d6..0000000 --- a/java/10_find.ipynb +++ /dev/null @@ -1,332 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "9d2c1c5d", - "metadata": {}, - "source": [ - "[![Lab Documentation and Solutions](https://img.shields.io/badge/Lab%20Documentation%20and%20Solutions-darkgreen)](https://mongodb-developer.github.io/vector-search-lab/)" - ] - }, - { - "cell_type": "markdown", - "id": "3b936925-e295-489a-b508-2b99c0160217", - "metadata": {}, - "source": [ - "# CRUD: Find\n", - " " - ] - }, - { - "cell_type": "markdown", - "id": "dependent-boundary", - "metadata": {}, - "source": [ - "## Import the MongoDB Driver using Maven" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", - " \n", - "import com.mongodb.client.MongoClient;\n", - "import com.mongodb.client.MongoClients;\n", - "import com.mongodb.client.MongoDatabase;\n", - "import com.mongodb.client.MongoCollection;\n", - "import com.mongodb.client.FindIterable;\n", - "import com.mongodb.client.model.Projections;\n", - "\n", - "import static com.mongodb.client.model.Filters.eq;\n", - "import static com.mongodb.client.model.Filters.gt;\n", - "import static com.mongodb.client.model.Filters.lt;\n", - "import static com.mongodb.client.model.Filters.and;\n", - "\n", - "import org.bson.conversions.Bson;\n", - "import org.bson.Document;\n", - "import org.bson.json.JsonWriterSettings;\n", - "\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": [ - "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\");" - ] - }, - { - "cell_type": "markdown", - "id": "automatic-fisher", - "metadata": {}, - "source": [ - "## Find one Book\n", - "\n", - "This is the R part in CRUD. We use [`find()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/find/)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "proof-syria", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "Document aBook = books.find().first();\n", - "\n", - "if (aBook != null) {\n", - " System.out.println(\"Book: \" + aBook.toJson());\n", - "} else {\n", - " System.out.println(\"Empty collection\");\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "handled-symbol", - "metadata": {}, - "source": [ - "## Find books written after 2008" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "african-maple", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "Bson booksAfter2008 = gt(\"year\", 2008);\n", - "\n", - "books.find(booksAfter2008)\n", - " .forEach(b -> System.out.println(\"Book: \" + b.toJson())); " - ] - }, - { - "cell_type": "markdown", - "id": "9f6caab3", - "metadata": {}, - "source": [ - "## Find all the books that have less than 50 pages and project only the title and pages" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "polar-pride", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "Bson booksWithLessThan50pages = lt(\"pages\", 50);\n", - "Bson showOnlyTitleAndPages = Projections.fields(Projections.include(\"title\", \"pages\"));\n", - "\n", - "books.find(booksWithLessThan50pages)\n", - " .projection(showOnlyTitleAndPages)\n", - " .forEach(b -> System.out.println(\"Book: \" + b.toJson()));" - ] - }, - { - "cell_type": "markdown", - "id": "1e62db28", - "metadata": {}, - "source": [ - "Exclude `_id` field" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ff5c7cb4", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "Bson booksWithLessThan50pages = lt(\"pages\", 50);\n", - "Bson showOnlyTitleAndPagesNoId = Projections.fields(\n", - " Projections.include(\"title\", \"pages\"),\n", - " Projections.excludeId()\n", - ");\n", - "\n", - "books.find(booksWithLessThan50pages)\n", - " .projection(showOnlyTitleAndPagesNoId)\n", - " .forEach(b -> System.out.println(\"Book: \" + b.toJson())); " - ] - }, - { - "cell_type": "markdown", - "id": "c93f57e4", - "metadata": {}, - "source": [ - "## Challenges" - ] - }, - { - "cell_type": "markdown", - "id": "f512e717", - "metadata": {}, - "source": [ - "### Find all books where totalInventory is exactly 5. \n", - "\n", - "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/WHERE#1-find-all-books-where-totalinventory-is-exactly-5)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f1f4085d", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// type in your code here\n" - ] - }, - { - "cell_type": "markdown", - "id": "627c4fb7", - "metadata": {}, - "source": [ - "### 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)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fd8a8143", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// type in your code here\n" - ] - }, - { - "cell_type": "markdown", - "id": "601d0b12", - "metadata": {}, - "source": [ - "### 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)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1a94638b", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// type in your code here\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "21.0.8+9-LTS" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/java/10_find_project.ipynb b/java/10_find_project.ipynb new file mode 100644 index 0000000..8863f68 --- /dev/null +++ b/java/10_find_project.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "9d2c1c5d", + "metadata": {}, + "source": [ + "[![Lab Documentation and Solutions](https://img.shields.io/badge/Lab%20Documentation%20and%20Solutions-darkgreen)](https://mongodb-developer.github.io/vector-search-lab/)" + ] + }, + { + "cell_type": "markdown", + "id": "3b936925-e295-489a-b508-2b99c0160217", + "metadata": {}, + "source": [ + "# CRUD: Find and Project\n", + "\n", + "## What can the `find()` operation do?\n", + "\n", + "The [Find documents](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/find/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) operation lets us query and retrieve documents from a MongoDB collection.\n", + "\n", + "In this section, we will use `find()` with filters such as `eq()`, `gt()`, `gte()`, and `and()` to search for documents and apply conditions.\n", + "\n", + "We will also use **projections** such as `fields()`, `include()`, and `excludeId()` to return only the fields we need." + ] + }, + { + "cell_type": "markdown", + "id": "dependent-boundary", + "metadata": {}, + "source": [ + "## Startup Code\n", + "\n", + "This cell imports the MongoDB Java driver and the helper classes we will use throughout the notebook. It also configures the connection to MongoDB, connects to the `library` database, and initializes the `books` collection used in the examples." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66ef28c4-f86b-4576-839e-100a7ae022c7", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "// Import the MongoDB Driver using Maven\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", + " \n", + "import com.mongodb.client.MongoClient;\n", + "import com.mongodb.client.MongoClients;\n", + "import com.mongodb.client.MongoDatabase;\n", + "import com.mongodb.client.MongoCollection;\n", + "import com.mongodb.client.FindIterable;\n", + "import com.mongodb.client.model.Projections;\n", + "\n", + "import static com.mongodb.client.model.Projections.fields;\n", + "import static com.mongodb.client.model.Projections.include;\n", + "import static com.mongodb.client.model.Projections.exclude;\n", + "import static com.mongodb.client.model.Projections.excludeId;\n", + "\n", + "import static com.mongodb.client.model.Filters.eq;\n", + "import static com.mongodb.client.model.Filters.gt;\n", + "import static com.mongodb.client.model.Filters.gte;\n", + "import static com.mongodb.client.model.Filters.and;\n", + "\n", + "import org.bson.conversions.Bson;\n", + "import org.bson.Document;\n", + "import org.bson.json.JsonWriterSettings;\n", + "\n", + "import java.util.ArrayList;\n", + "import java.util.List;\n", + "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", + "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", + "\n", + "MongoClient mongoClient = null;\n", + "\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\");" + ] + }, + { + "cell_type": "markdown", + "id": "automatic-fisher", + "metadata": {}, + "source": [ + "## Find one book\n", + "\n", + "This is the **Read** part of CRUD. We use [`find()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/find/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to query documents from a collection.\n", + "\n", + "In this example, `find()` returns the query result, and `first()` retrieves the first matching document from the `books` collection." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "proof-syria", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "Document firstBook = books.find().first();\n", + "\n", + "if (firstBook != null) {\n", + " System.out.println(\"Book: \" + firstBook.toJson());\n", + "} else {\n", + " System.out.println(\"No book was found.\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "bfe14885", + "metadata": {}, + "source": [ + "# Find and Project\n", + "\n", + "In this example, we use [`eq()`](https://www.mongodb.com/docs/manual/reference/operator/query/eq/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to find the book with the title `\"Treasure of the Sun\"` and [`project`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to return only the `title`, `_id` and `pages` fields." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d27da2f", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "var filter = eq(\"title\", \"Treasure of the Sun\");\n", + "var projection = include(\"title\", \"pages\");\n", + "\n", + "books.find(filter)\n", + " .projection(projection)\n", + " .forEach(b -> System.out.println(b.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "handled-symbol", + "metadata": {}, + "source": [ + "## Find books written after 2021\n", + "\n", + "In this example, we use [`gt()`](https://www.mongodb.com/docs/manual/reference/operator/query/gt/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello), which means **greater than**, to filter books whose `year` is greater than `2021`, and project only the `title`, `_id` and `year`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "african-maple", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "filter = gt(\"year\", 2021);\n", + "projection = include(\"title\", \"year\");\n", + "\n", + "books.find(filter)\n", + " .projection(projection)\n", + " .forEach(b -> System.out.println(b.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "9f6caab3", + "metadata": {}, + "source": [ + "## Find all books with 2000 pages or more\n", + "\n", + "We use [`gte()`](https://www.mongodb.com/docs/manual/reference/operator/query/gte/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello), which means **greater than or equal to**, to filter books whose `pages` value is `2000` or higher.\n", + "\n", + "Then, we use a projection to return the `title`, `genres`, and `_id` fields." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "polar-pride", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "filter = gte(\"pages\", 2000);\n", + "projection = include(\"title\", \"year\", \"genres\");\n", + "\n", + "books.find(filter)\n", + " .projection(projection)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "1e62db28", + "metadata": {}, + "source": [ + "## Exclude the `_id` Field\n", + "\n", + "In the previous example, MongoDB still returned the `_id` field because it is included by default, even when we do not explicitly list it in the projection.\n", + "\n", + "To remove it, we use [`excludeId()`](https://www.mongodb.com/docs/drivers/java/sync/current/builders/projections/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello). To combine `excludeId()` with `include()`, we wrap them with `fields()`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff5c7cb4", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "projection = fields(\n", + " include(\"title\", \"pages\"),\n", + " excludeId()\n", + ");\n", + "\n", + "books.find(filter)\n", + " .projection(projection)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "c93f57e4", + "metadata": {}, + "source": [ + "## Challenges" + ] + }, + { + "cell_type": "markdown", + "id": "f512e717", + "metadata": {}, + "source": [ + "### Find books with a `totalInventory` of 5\n", + "\n", + "Use a filter to return books where `totalInventory` is exactly `5`.\n", + "\n", + "_Hint: Consider projecting only the fields you actually need in the results._\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/WHERE#1-find-all-books-where-totalinventory-is-exactly-5/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1f4085d", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "//TYPE YOUR CODE HERE\n", + "Bson filter = ;\n", + "\n", + "books.find(filter)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "627c4fb7", + "metadata": {}, + "source": [ + "### Find books with more than 300 pages\n", + "\n", + "Use a filter to return books where the `pages` value is greater than `300`.\n", + "\n", + "_Hint: Project only the fields you need to keep the results clean and focused._\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/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd8a8143", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "//TYPE YOUR CODE HERE\n", + "Bson filter = ;\n", + "\n", + "books.find(filter)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "601d0b12", + "metadata": {}, + "source": [ + "### Find Science books with more than 300 pages\n", + "\n", + "Use multiple filter conditions to return books where the `genres` field contains `\"Science\"` and the `pages` value is greater than `300`.\n", + "\n", + "_Hint: Consider projecting only the fields you actually need in the results._\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/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1a94638b", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "//TYPE YOUR CODE HERE\n", + "Bson filter = and(\n", + " ,\n", + " \n", + ");\n", + "\n", + "books.find(filter)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "63641ae4", + "metadata": {}, + "source": [ + "### Retrieve only the `title` field for all books\n", + "\n", + "Use a projection to return only the `title` field from documents in the `books` collection.\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/SELECT#-1-retrieve-only-the-title-field-for-all-books?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9e055996", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "//TYPE YOUR CODE HERE\n", + "Bson projection = ;\n", + "\n", + "books.find()\n", + " .projection(projection)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + }, + { + "cell_type": "markdown", + "id": "967defc4", + "metadata": {}, + "source": [ + "### Retrieve all fields except `_id` and `authors` for books in the `\"History\"` genre\n", + "\n", + "Use a filter to match books in the `\"History\"` genre, then use a projection to exclude the `_id` and `authors` fields from the result.\n", + "\n", + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/SELECT#-2-retrieve-all-fields-except-_id-and-authors-for-books-in-the-history-genre?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0db3d126", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "//TYPE YOUR CODE HERE\n", + "Bson filter = ;\n", + "Bson projection = ;\n", + "\n", + "books.find(genreFilter)\n", + " .projection(projection)\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Java", + "language": "java", + "name": "java" + }, + "language_info": { + "codemirror_mode": "java", + "file_extension": ".jshell", + "mimetype": "text/x-java-source", + "name": "Java", + "pygments_lexer": "java", + "version": "21.0.8+9-LTS" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 52588ba9421864359f8ca47d3b2b8f8b9c26c1b8 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 19:09:01 -0300 Subject: [PATCH 3/9] renaming project sort file --- java/{20_project_sort_limit.ipynb => 20_sort_limit.ipynb} | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename java/{20_project_sort_limit.ipynb => 20_sort_limit.ipynb} (98%) diff --git a/java/20_project_sort_limit.ipynb b/java/20_sort_limit.ipynb similarity index 98% rename from java/20_project_sort_limit.ipynb rename to java/20_sort_limit.ipynb index 420cb41..3645272 100644 --- a/java/20_project_sort_limit.ipynb +++ b/java/20_sort_limit.ipynb @@ -37,7 +37,8 @@ "outputs": [], "source": [ "// Import the MongoDB Driver using Maven\n", - "%maven org.mongodb:mongodb-driver-sync:5.0.0\n", + "%maven org.mongodb:mongodb-driver-sync:5.5.1\n", + "%maven org.slf4j:slf4j-simple:1.7.36\n", " \n", "import com.mongodb.client.MongoClient;\n", "import com.mongodb.client.MongoClients;\n", From 3731578e49c4bbda23dddac821155fabf20979e9 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 19:43:17 -0300 Subject: [PATCH 4/9] Improve Sort & Limit section with clearer explanations and examples - Added explanatory text for sort(), limit(), and skip() - Improved scenario descriptions and renamed variables for better readability - Adjusted examples to better match the workshop flow - Added documentation links with UTM tracking - Removed duplicated exercises already covered in the Find section --- java/20_sort_limit.ipynb | 137 ++++++++++++++++++--------------------- 1 file changed, 63 insertions(+), 74 deletions(-) diff --git a/java/20_sort_limit.ipynb b/java/20_sort_limit.ipynb index 3645272..d729deb 100644 --- a/java/20_sort_limit.ipynb +++ b/java/20_sort_limit.ipynb @@ -13,8 +13,13 @@ "id": "3b936925-e295-489a-b508-2b99c0160217", "metadata": {}, "source": [ - "# CRUD: Project, Sort & Limit\n", - " " + "# CRUD: Sort & Limit\n", + "\n", + "## What can `sort()` and `limit()` do?\n", + "\n", + "The [`sort()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/sort/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) and [`limit()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/limit/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) operations let us control the order and number of documents returned by a query.\n", + "\n", + "In this section, we will sort documents in ascending or descending order and limit how many results are returned from the collection." ] }, { @@ -22,7 +27,9 @@ "id": "13926b8c", "metadata": {}, "source": [ - "## Startup code" + "## Startup code\n", + "\n", + "This cell imports the MongoDB Java Driver and helper classes, establishes the connection to MongoDB, and initializes the `library` database and `books` collection used throughout the CRUD examples." ] }, { @@ -48,8 +55,14 @@ "import com.mongodb.client.model.Sorts;\n", "import com.mongodb.client.model.Projections;\n", "\n", + "import static com.mongodb.client.model.Projections.fields;\n", + "import static com.mongodb.client.model.Projections.excludeId;\n", + "import static com.mongodb.client.model.Projections.include;\n", + "\n", + "import static com.mongodb.client.model.Sorts.ascending;\n", "import static com.mongodb.client.model.Sorts.descending;\n", - "import static com.mongodb.client.model.Filters.eq;\n", + "\n", + "import static com.mongodb.client.model.Filters.lte;\n", "\n", "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", @@ -58,6 +71,10 @@ "import java.util.ArrayList;\n", "import java.util.List;\n", "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", "// Set your connection String\n", "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", "\n", @@ -79,7 +96,9 @@ "id": "automatic-fisher", "metadata": {}, "source": [ - "## Sort books by descending number of pages\n" + "## Sort books by descending number of pages\n", + "\n", + "In this example, we use [`lte()`](https://www.mongodb.com/docs/manual/reference/operator/query/lte/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to filter books published before or in `1930`, project only the `title` and `pages` fields, and use [`sort()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/sort/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to order the results by the number of pages in descending order." ] }, { @@ -93,16 +112,16 @@ }, "outputs": [], "source": [ - "Bson projection = Projections.include(\"title\", \"pages\");\n", - "\n", "FindIterable cursor = books \n", - " .find() // empty filter: all books \n", - " .projection(projection) // projection \n", - " .sort(Sorts.descending(\"pages\")); // sort by pages descending \n", + " .find(lte(\"year\", 1930)) \n", + " .projection(\n", + " fields(excludeId(), include(\"title\", \"pages\"))\n", + " )\n", + " .sort(descending(\"pages\")); \n", "\n", "for (Document book : cursor) { \n", " System.out.println(book.toJson()); \n", - "} " + "}" ] }, { @@ -110,7 +129,9 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "## Limit" + "## Retrieve the top 5 longest books\n", + "\n", + "In this example, we retrieve all books, project only the `title` and `pages` fields, sort the results by the number of pages in descending order, and use [`limit()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/limit/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to return only the first 5 documents." ] }, { @@ -124,13 +145,11 @@ }, "outputs": [], "source": [ - "Bson projection = Projections.include(\"title\", \"pages\"); // projection \n", - "\n", "FindIterable cursor = books \n", - " .find() // empty filter: all books \n", - " .projection(projection) // projection \n", - " .sort(Sorts.descending(\"pages\")) // sort by pages descending \n", - " .limit(5); // limit to 5 documents\n", + " .find() \n", + " .projection(include(\"title\", \"pages\")) \n", + " .sort(descending(\"pages\")) \n", + " .limit(5); \n", "\n", "for (Document book : cursor) { \n", " System.out.println(book.toJson()); \n", @@ -142,7 +161,9 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "## Chaining methods with find" + "## Skip the first 180 books and retrieve the next 5\n", + "\n", + "In this example, we project only the `title` and `pages` fields, sort the books by the number of pages in ascending order, use [`skip()`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/query-documents/skip/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to ignore the first 180 matching documents, and return the next 5 results." ] }, { @@ -156,18 +177,18 @@ }, "outputs": [], "source": [ - "Bson projection = Projections.include(\"title\", \"pages\"); // projection \n", + "Bson projection = Projections.include(\"title\", \"pages\");\n", "\n", - "FindIterable cursor = books \n", - " .find() // empty filter: all books \n", - " .projection(projection) // projection \n", - " .sort(Sorts.descending(\"pages\")) // sort by pages descending \n", - " .skip(4) // skip first 4 documents\n", - " .limit(5); // limit to 5 documents\n", + "FindIterable cursor = books\n", + " .find()\n", + " .projection(projection)\n", + " .sort(ascending(\"pages\"))\n", + " .skip(180)\n", + " .limit(5);\n", "\n", - "for (Document book : cursor) { \n", - " System.out.println(book.toJson()); \n", - "} " + "for (Document book : cursor) {\n", + " System.out.println(book.toJson());\n", + "}" ] }, { @@ -180,42 +201,20 @@ }, { "cell_type": "markdown", - "id": "00153c48", + "id": "1714facc", "metadata": {}, "source": [ - "### Retrieve only the title field for all books.\n", + "### Find the first 10 books alphabetically by title\n", "\n", - "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/SELECT#-1-retrieve-only-the-title-field-for-all-books)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4a4f8e26", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// type your code here" - ] - }, - { - "cell_type": "markdown", - "id": "ffea41f8", - "metadata": {}, - "source": [ - "### Retrieve all fields except _id and authors for books in the \"History\" genre.\n", + "_Hint: Use `sort()` with ascending order on the `title` field and combine it with `limit()` to return only 10 documents._\n", "\n", - "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/SELECT#-2-retrieve-all-fields-except-_id-and-authors-for-books-in-the-history-genre)" + "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/ORDER-LIMIT#-1-find-the-first-10-books-alphabetically-by-title?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" ] }, { "cell_type": "code", "execution_count": null, - "id": "f02579f7", + "id": "5409c76d", "metadata": { "vscode": { "languageId": "java" @@ -223,31 +222,21 @@ }, "outputs": [], "source": [ - "// type your code here\n" + "//TYPE YOUR CODE HERE\n", + "books.find()\n", + " .sort()\n", + " .limit()\n", + " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" ] }, { "cell_type": "markdown", - "id": "1714facc", + "id": "bc2d6bee", "metadata": {}, "source": [ - "### Find the first 10 books alphabetically by title.\n", + "## Summary\n", "\n", - "[Solution here](https://mongodb-developer.github.io/sql-to-query-api-lab/docs/CRUD/ORDER-LIMIT#-1-find-the-first-10-books-alphabetically-by-title)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5409c76d", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// type your code here\n" + "In this section, we learned how to use `sort()`, `skip()`, and `limit()` to control the order and number of documents returned by a query. These operations are commonly combined with `find()` to build more efficient and readable queries." ] } ], From a415b149b44c0854158f3a2b4a3739ed444bd4e7 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 19:43:26 -0300 Subject: [PATCH 5/9] Added summary --- java/10_find_project.ipynb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/java/10_find_project.ipynb b/java/10_find_project.ipynb index 8863f68..bdcb16d 100644 --- a/java/10_find_project.ipynb +++ b/java/10_find_project.ipynb @@ -415,6 +415,18 @@ " .projection(projection)\n", " .forEach(book -> System.out.println(\"Book: \" + book.toJson()));" ] + }, + { + "cell_type": "markdown", + "id": "8c3f11c5", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this section, we learned how to use `find()` to query documents from a MongoDB collection and apply filters such as `eq()`, `gt()`, `gte()`, and `and()` to narrow down the results.\n", + "\n", + "We also explored projections with `include()`, `excludeId()`, and `fields()` to control which fields are returned, helping us retrieve only the data we actually need." + ] } ], "metadata": { From c7d46a86d22f7ee125392d945e60465642a8da18 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 20:17:00 -0300 Subject: [PATCH 6/9] Improve array query examples and explanations - Added explanations for querying array fields with eq(), all(), and in() - Added examples demonstrating exact array matching behavior - Improved descriptions around array order and matching semantics - Added official MongoDB documentation links with UTM tracking - Refined examples and variable names for better readability --- java/11_find_arrays.ipynb | 114 +++++++++++++++++++++++++++++++------- 1 file changed, 95 insertions(+), 19 deletions(-) diff --git a/java/11_find_arrays.ipynb b/java/11_find_arrays.ipynb index b82c607..69334e1 100644 --- a/java/11_find_arrays.ipynb +++ b/java/11_find_arrays.ipynb @@ -13,8 +13,13 @@ "id": "3b936925-e295-489a-b508-2b99c0160217", "metadata": {}, "source": [ - "# CRUD: Find in arrays\n", - " " + "# CRUD: Querying Array Fields\n", + "\n", + "## How can we query array fields in MongoDB?\n", + "\n", + "MongoDB lets us [query an array](https://www.mongodb.com/docs/manual/tutorial/query-arrays/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) fields in different ways depending on the matching behavior we want.\n", + "\n", + "In this section, we will use operators such as `all()`, `in()`, and `eq()` to find documents where array fields contain specific values, multiple values, or exact array matches." ] }, { @@ -22,7 +27,9 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Startup code\n" + "## Startup code\n", + "\n", + "This cell imports the MongoDB Java Driver, connects to MongoDB, and initializes the `library` database and `books` collection used in the examples." ] }, { @@ -46,17 +53,22 @@ "import com.mongodb.client.MongoCollection;\n", "import com.mongodb.client.FindIterable;\n", "\n", + "import static com.mongodb.client.model.Projections.include;\n", + "\n", "import static com.mongodb.client.model.Filters.eq;\n", "import static com.mongodb.client.model.Filters.all;\n", "import static com.mongodb.client.model.Filters.in;\n", "\n", "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", - "import org.bson.json.JsonWriterSettings;\n", "\n", - "import java.util.ArrayList;\n", "import java.util.List;\n", "\n", + "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", "// Set your connection String\n", "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", "\n", @@ -78,7 +90,9 @@ "id": "automatic-fisher", "metadata": {}, "source": [ - "## Find all books containing one genre\n" + "## Find books that contain `Poetry`\n", + "\n", + "In this example, we use [`eq()`](https://www.mongodb.com/docs/manual/reference/operator/query/eq/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to find books where the `genres` array contains the value `\"Poetry\"`.\n" ] }, { @@ -92,8 +106,11 @@ }, "outputs": [], "source": [ - "Bson poetryBooks = eq(\"genres\", \"Poetry\");\n", - "books.find(poetryBooks)\n", + "Bson filter = eq(\"genres\", \"Poetry\");\n", + "Bson projection = include(\"title\", \"genres\");\n", + "\n", + "books.find(filter)\n", + " .projection(projection)\n", " .forEach(b -> System.out.println(\"Book: \" + b.toJson()));" ] }, @@ -102,7 +119,9 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "## Find all books containing the listed genres (AND)" + "## Find books that contain both `Family Life` and `Fiction` (AND)\n", + "\n", + "In this example, we use [`all()`](https://www.mongodb.com/docs/manual/reference/operator/query/all/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to find books where the `genres` array contains both `\"Family Life\"` and `\"Fiction\"`.\n" ] }, { @@ -116,9 +135,10 @@ }, "outputs": [], "source": [ - "Bson familyLifeAndFictionBooks = all(\"genres\", \"Family Life\", \"Fiction\");\n", + "filter = all(\"genres\", \"Family Life\", \"Fiction\");\n", "\n", - "books.find(familyLifeAndFictionBooks)\n", + "books.find(filter)\n", + " .projection(projection)\n", " .forEach(b -> System.out.println(\"Book: \" + b.toJson()));" ] }, @@ -127,7 +147,9 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "## Find all books containing at least one of the listed genres (OR)" + "## Find books that contain `Family Life` or `Fiction` (OR)\n", + "\n", + "In this example, we use [`in()`](https://www.mongodb.com/docs/manual/reference/operator/query/in/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) to find books where the `genres` array contains either `\"Family Life\"` or `\"Fiction\"`.\n" ] }, { @@ -141,9 +163,10 @@ }, "outputs": [], "source": [ - "Bson familyLifeOrFictionBooks = in(\"genres\", \"Family Life\", \"Fiction\");\n", + "filter = in(\"genres\", \"Family Life\", \"Fiction\");\n", "\n", - "books.find(familyLifeOrFictionBooks)\n", + "books.find(filter)\n", + " .projection(projection)\n", " .forEach(b -> System.out.println(\"Book: \" + b.toJson()));" ] }, @@ -152,9 +175,15 @@ "id": "1e62db28", "metadata": {}, "source": [ - "## Don't make this mistake!\n", + "## Understanding exact array matches\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." + "When using [`eq()`](https://www.mongodb.com/docs/manual/reference/operator/query/eq/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) with an array, MongoDB looks for an **exact array match**.\n", + "\n", + "This means:\n", + "- the values must be the same\n", + "- the order must also match exactly\n", + "\n", + "For example, the query below returns a document because the `genres` array is exactly `[\"Poetry\", \"American\"]`." ] }, { @@ -168,10 +197,57 @@ }, "outputs": [], "source": [ - "Bson poetryAndFictionBooks = eq(\"genres\", Arrays.asList(\"Poetry\", \"Fiction\"));\n", + "filter = eq(\"genres\", List.of(\"Poetry\", \"American\"));\n", "\n", - "books.find(poetryAndFictionBooks)\n", - " .forEach(b -> System.out.println(\"Book: \" + b.toJson()));" + "Document result = books.find(filter).projection(projection).first();\n", + "\n", + "if (result != null) {\n", + " System.out.println(\"Book: \" + result.toJson());\n", + "} else {\n", + " System.out.println(\"No matching books were found.\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "7b829347", + "metadata": {}, + "source": [ + "However, if we invert the values to `[\"American\", \"Poetry\"]`, the query does not return any documents because the array order no longer matches the stored document exactly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5d36e87", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "filter = eq(\"genres\", List.of(\"American\", \"Poetry\"));\n", + "\n", + "Document result = books.find(filter).projection(projection).first();\n", + "\n", + "if (result != null) {\n", + " System.out.println(\"Book: \" + result.toJson());\n", + "} else {\n", + " System.out.println(\"No matching books were found.\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "aa28eb2d", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this section, we learned different ways to query array fields in MongoDB using operators such as `eq()`, `all()`, and `in()`.\n", + "\n", + "We also explored how exact array matching works, including the importance of element order when comparing entire arrays with `eq()`." ] } ], From 770dae1bc7dd48006c05f5b35eef9a6c2e52ceca Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 20:25:16 -0300 Subject: [PATCH 7/9] Improve Insert CRUD section and exercises - Added introductory explanations for insert operations - Added examples using insertOne() and insertMany() - Improved challenge descriptions and hints - Added examples of review documents for guidance - Added MongoDB documentation links with UTM tracking - Refined wording and examples for better readability --- java/30_insert.ipynb | 63 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/java/30_insert.ipynb b/java/30_insert.ipynb index 08c5af3..0472696 100644 --- a/java/30_insert.ipynb +++ b/java/30_insert.ipynb @@ -14,7 +14,12 @@ "metadata": {}, "source": [ "# Basic CRUD: Insert\n", - " " + "\n", + "## What can the `insert` operation do?\n", + "\n", + "The [`insert`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/insert/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) operations let us add new documents to a MongoDB collection.\n", + "\n", + "In this section, we will use operations such as `insertOne()` and `insertMany()` to create and store documents in the `books` collection." ] }, { @@ -22,7 +27,9 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Startup code" + "## Startup code\n", + "\n", + "This cell imports the MongoDB Java Driver, connects to MongoDB, and initializes the `library` database and `books` collection used in the insert examples." ] }, { @@ -52,6 +59,10 @@ "\n", "import java.util.List;\n", "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", "// Set your connection String\n", "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", "\n", @@ -81,7 +92,9 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "### Insert one book" + "### Insert one book\n", + "\n", + "In this example, we create a new `Document` representing a book and use `insertOne()` to add it to the `books` collection." ] }, { @@ -106,7 +119,9 @@ "id": "worth-windows", "metadata": {}, "source": [ - "### Read the book we just inserted, using the year" + "### Find the inserted document\n", + "\n", + "In this example, we query the `books` collection to verify that the document inserted with the year `1500` was successfully stored in MongoDB." ] }, { @@ -131,7 +146,11 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "### Can you find the same document, but using the `_id` instead? Fix the code below!" + "### Find the same document using the `_id`\n", + "\n", + "Can you find the same document again, but this time using the `_id` field instead of the `year`?\n", + "\n", + "Fix the code below by adding the correct `ObjectId`." ] }, { @@ -166,7 +185,20 @@ "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)" + "_Hint: Use `insertMany()` with a `List.of()` containing multiple `Document` objects._\n", + "\n", + "Example review document:\n", + "\n", + "```json\n", + "{\n", + " \"text\": \"Amazing book!\",\n", + " \"rating\": 5,\n", + " \"name\": \"Ricardo\",\n", + " \"bookId\": \"0786222727\"\n", + "}\n", + "````\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?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" ] }, { @@ -180,8 +212,23 @@ }, "outputs": [], "source": [ - "// type your code here\n", - " " + "// TYPE YOUR CODE HERE\n", + "\n", + "var reviews = library.getCollection(\"reviews\");\n", + "\n", + ";" + ] + }, + { + "cell_type": "markdown", + "id": "7e9330dd", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this section, we learned how to insert new documents into MongoDB using operations such as `insertOne()` and `insertMany()`.\n", + "\n", + "We also explored how MongoDB automatically generates `_id` values and how inserted documents can be queried afterward." ] } ], From 4a64684a2ec668b927cd2cc1bc8ac905f30a2db4 Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 20:30:55 -0300 Subject: [PATCH 8/9] Improve Delete CRUD section and exercises - Added introductory explanations for delete operations - Added examples using deleteOne() and deleteMany() - Improved delete challenge instructions and hints - Refined filter and variable naming for better readability - Added MongoDB documentation links with UTM tracking - Added explanations about DeleteResult and deleted document counts --- java/40_delete.ipynb | 66 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/java/40_delete.ipynb b/java/40_delete.ipynb index f4b9454..0e07e3f 100644 --- a/java/40_delete.ipynb +++ b/java/40_delete.ipynb @@ -13,8 +13,13 @@ "id": "3b936925-e295-489a-b508-2b99c0160217", "metadata": {}, "source": [ - "# CRUD: Delete\n", - " " + "# Basic CRUD: Delete\n", + "\n", + "## What can the `delete` operation do?\n", + "\n", + "The [`delete`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/delete/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) operations let us remove documents from a MongoDB collection.\n", + "\n", + "In this section, we will use operations such as `deleteOne()` and `deleteMany()` to remove documents from the `books` collection." ] }, { @@ -54,6 +59,10 @@ "\n", "import java.util.List;\n", "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", "// Set your connection String\n", "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", "\n", @@ -77,7 +86,7 @@ "source": [ "## Insert one book\n", "\n", - "We want to make sure this book is in the collection, so we can later delete it." + "We want to make sure this book exists in the collection so we can later remove it using a delete operation." ] }, { @@ -91,12 +100,10 @@ }, "outputs": [], "source": [ - "Document platero = new Document();\n", - "\n", - "platero\n", - " .append(\"_id\", \"platero\")\n", - " .append(\"title\", \"Platero y yo\")\n", - " .append(\"year\", 1900);\n", + "Document platero = new Document()\n", + " .append(\"_id\", \"platero\")\n", + " .append(\"title\", \"Platero y yo\")\n", + " .append(\"year\", 1900);\n", "\n", "books.insertOne(platero);" ] @@ -106,7 +113,9 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "### We find the document we just inserted using the `_id` field" + "### Find the inserted book\n", + "\n", + "In this example, we query the `books` collection using the `_id` field to confirm that the `Platero y yo` document exists before deleting it." ] }, { @@ -131,7 +140,11 @@ "id": "worth-windows", "metadata": {}, "source": [ - "### Delete that book" + "### Delete one book\n", + "\n", + "In this example, we use `deleteOne()` to remove the document with `_id` equal to `\"platero\"` from the `books` collection. \n", + "\n", + "The returned `DeleteResult` lets us verify how many documents were deleted." ] }, { @@ -145,12 +158,13 @@ }, "outputs": [], "source": [ - "Document bookFrom1500 = new Document(\"year\", 1500);\n", + "Document plateroFilter = new Document(\"_id\", \"platero\");\n", "\n", - "DeleteResult deleteResult = books.deleteOne(new Document(\"_id\", \"platero\"));\n", + "DeleteResult deleteResult = books.deleteOne(plateroFilter);\n", "\n", "// Check the number of deleted documents\n", "long deletedCount = deleteResult.getDeletedCount();\n", + "\n", "System.out.println(\"Deleted \" + deletedCount + \" document(s).\");" ] }, @@ -169,6 +183,10 @@ "source": [ "### Delete all the reviews for bookId \"0786222727\" through a single command.\n", "\n", + "\n", + "_Hint: You may need an operation capable of deleting multiple documents at once._\n", + "\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)" ] }, @@ -183,7 +201,27 @@ }, "outputs": [], "source": [ - "// type your code here\n" + "//TYPE YOUR CODE HERE\n", + "\n", + "MongoCollection reviews = library.getCollection(\"reviews\");\n", + "\n", + "Bson filter = ;\n", + "\n", + "DeleteResult result = ;\n", + "\n", + "System.out.println(result.getDeletedCount() + \" reviews deleted.\");" + ] + }, + { + "cell_type": "markdown", + "id": "7920a719", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this section, we learned how to remove documents from MongoDB using operations such as `deleteOne()` and `deleteMany()`.\n", + "\n", + "We also explored how to verify deleted documents before removal and how to use `DeleteResult` to confirm how many documents were deleted." ] } ], From bc8a8890c97ec010e08d1e4820dd5fc2d6fa04cc Mon Sep 17 00:00:00 2001 From: Ricardo Mello Date: Fri, 22 May 2026 20:43:49 -0300 Subject: [PATCH 9/9] Improve Update CRUD section and examples - Added introductory explanations for update operations - Added examples using updateOne(), set(), addToSet(), and currentTimestamp() - Added upsert examples and explanations - Improved challenge instructions and hints - Refined code formatting and variable naming for readability - Added MongoDB documentation links with UTM tracking --- java/40_delete.ipynb | 4 +- java/50_update.ipynb | 128 +++++++++++++++++++++++++++++++++---------- 2 files changed, 101 insertions(+), 31 deletions(-) diff --git a/java/40_delete.ipynb b/java/40_delete.ipynb index 0e07e3f..e84e188 100644 --- a/java/40_delete.ipynb +++ b/java/40_delete.ipynb @@ -27,7 +27,9 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Startup code" + "## Startup code\n", + "\n", + "This cell imports the MongoDB Java Driver, connects to MongoDB, and initializes the `library` database and `books` collection used in the delete examples." ] }, { diff --git a/java/50_update.ipynb b/java/50_update.ipynb index df14164..2673e00 100644 --- a/java/50_update.ipynb +++ b/java/50_update.ipynb @@ -13,8 +13,13 @@ "id": "3b936925-e295-489a-b508-2b99c0160217", "metadata": {}, "source": [ - "# CRUD: Update\n", - " " + "# Basic CRUD: Update\n", + "\n", + "## What can the `update` operation do?\n", + "\n", + "The [`update`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/update-documents/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) operations let us modify existing documents in a MongoDB collection.\n", + "\n", + "In this section, we will use operations such as `updateOne()` and `updateMany()` to update fields in documents from the `books` collection." ] }, { @@ -22,7 +27,9 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Startup code" + "## Startup code\n", + "\n", + "This cell imports the MongoDB Java Driver, connects to MongoDB, and initializes the `library` database and `books` collection used in the update examples." ] }, { @@ -57,6 +64,10 @@ "import org.bson.Document;\n", "import org.bson.conversions.Bson;\n", "\n", + "// Configure SLF4J Simple Logger to suppress MongoDB driver logs in the notebook output.\n", + "System.setProperty(\"org.slf4j.simpleLogger.defaultLogLevel\", \"off\");\n", + "System.setProperty(\"org.slf4j.simpleLogger.log.org.mongodb.driver\", \"off\");\n", + "\n", "// Set your connection String\n", "String connectionString = \"mongodb://admin:mongodb@localhost:27017/\";\n", "\n", @@ -78,7 +89,10 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "## Insert one book" + "## Insert one book\n", + "\n", + "In this example, we insert a new document into the `books` collection. \n", + "We will later update this same document using `updateOne()`." ] }, { @@ -92,8 +106,7 @@ }, "outputs": [], "source": [ - "Document elQuijote = new Document();\n", - "elQuijote\n", + "Document elQuijote = new Document()\n", " .append(\"_id\", \"quijote\")\n", " .append(\"title\", \"El Quijote\")\n", " .append(\"year\", 1501);\n", @@ -106,7 +119,9 @@ "id": "9f6caab3", "metadata": {}, "source": [ - "### Show the inserted book" + "### Find inserted book\n", + "\n", + "Before updating the document, we query the `books` collection to confirm that the `El Quijote` document was successfully inserted." ] }, { @@ -135,15 +150,14 @@ } }, "source": [ - "### Update that book" - ] - }, - { - "cell_type": "markdown", - "id": "50ea627a", - "metadata": {}, - "source": [ - "Use the 📗 [updateOne](https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/updateOne/) documentation." + "### Update the inserted book\n", + "\n", + "In this example, we use `updateOne()` to modify the `El Quijote` document.\n", + "\n", + "The update operation:\n", + "- adds a new field called `newField`\n", + "- adds `\"Chivalry\"` to the `genres` array\n", + "- updates the `lastUpdated` field with the current timestamp" ] }, { @@ -186,7 +200,9 @@ "id": "737b00e6", "metadata": {}, "source": [ - "Now check the contents of the book, that has changed!" + "### Verify the updated document \n", + "\n", + "After running the update operation, we query the `books` collection again to confirm that the document was successfully modified." ] }, { @@ -205,20 +221,19 @@ "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" + "## Understanding `upsert`\n", + "\n", + "[`upsert`](https://www.mongodb.com/docs/drivers/java/sync/current/crud/update-documents/upsert/?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello) combines **update** and **insert** behavior in a single operation.\n", + "\n", + "If a matching document exists, MongoDB updates it. \n", + "If no document matches the filter, MongoDB inserts a new one instead.\n", + "\n", + "To demonstrate this behavior, we first delete the `El Quijote` document so it no longer exists in the collection." ] }, { @@ -244,7 +259,9 @@ "id": "e5ddfd06", "metadata": {}, "source": [ - "### Upsert: we try to update it but will get inserted instead" + "### Run the update operation with `upsert`\n", + "\n", + "Now that the document no longer exists in the collection, we run the update operation again with `upsert(true)` enabled." ] }, { @@ -282,6 +299,36 @@ "}" ] }, + { + "cell_type": "markdown", + "id": "e93a39fc", + "metadata": {}, + "source": [ + "### Verify the upserted document\n", + "\n", + "Since the document did not exist, MongoDB inserted a new one during the update operation with `upsert(true)` enabled.\n", + "\n", + "We can now query the collection again to confirm that the document was created." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "383fd2e3", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "source": [ + "Document upsertedBook = books.find(\n", + " new Document(\"_id\", \"quijote\")\n", + ").first();\n", + "\n", + "System.out.println(\"Book: \" + upsertedBook.toJson());" + ] + }, { "cell_type": "markdown", "id": "b8bfa616", @@ -295,9 +342,11 @@ "id": "fe70e1e8", "metadata": {}, "source": [ - "### Update the pages of the book \"Treasure of the Sun\" to 449.\n", + "### 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)" + "_Hint: Use `updateOne()` together with `Updates.set()` to modify the value of a single field._\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?utm_campaign=devrel&utm_source=third-part-content&utm_medium=cta&utm_content=crud-operations-java-workshop&utm_term=ricardo.mello)" ] }, { @@ -311,7 +360,26 @@ }, "outputs": [], "source": [ - "// type your code here\n" + "//TYPE YOUR CODE HERE\n", + "\n", + "var query = ;\n", + "var update = ;\n", + "\n", + "UpdateResult updateResult = ;\n", + "\n", + "System.out.println(\"Modified document count: \" + updateResult.getModifiedCount());" + ] + }, + { + "cell_type": "markdown", + "id": "6865fa4c", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "In this section, we learned how to modify existing documents in MongoDB using operations such as `updateOne()` and update operators like `set()` and `addToSet()`.\n", + "\n", + "We also explored `upsert` behavior, where MongoDB inserts a new document if no existing document matches the update filter." ] } ],