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, 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/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/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, 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, diff --git a/java/50_update.ipynb b/java/50_update.ipynb index 5706c42..f6b99f0 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, "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,14 +66,18 @@ "id": "handled-symbol", "metadata": {}, "source": [ - "### Insert one book" + "## Insert one book" ] }, { "cell_type": "code", "execution_count": null, "id": "african-maple", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "Document elQuijote = new Document();\n", @@ -122,7 +101,11 @@ "cell_type": "code", "execution_count": null, "id": "polar-pride", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import org.bson.types.ObjectId;\n", @@ -164,7 +147,11 @@ "cell_type": "code", "execution_count": null, "id": "91c58788", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "source": [ "import org.bson.Document;\n", @@ -210,13 +197,135 @@ "cell_type": "code", "execution_count": null, "id": "8a6156ed", - "metadata": {}, + "metadata": { + "vscode": { + "languageId": "java" + } + }, "outputs": [], "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": null, + "id": "ac704a84", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "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": null, + "id": "bd6931b0", + "metadata": { + "vscode": { + "languageId": "java" + } + }, + "outputs": [], + "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": [], + "source": [ + "// type your code here\n" + ] } ], "metadata": { @@ -229,9 +338,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..f5630e6 100644 --- a/java/60_indexes.ipynb +++ b/java/60_indexes.ipynb @@ -21,7 +21,7 @@ "id": "dependent-boundary", "metadata": {}, "source": [ - "## Import the MongoDB Driver using Maven" + "## Startup code" ] }, { @@ -42,29 +42,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\");" ] }, { @@ -86,25 +79,13 @@ }, "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" + "}" ] }, { @@ -298,7 +279,7 @@ "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", - "version": "21.0.7+6-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." ] }, {