From 41b4cc856ed5feed7eba8bffa1ae816dd88ba610 Mon Sep 17 00:00:00 2001 From: Mike Woofter Date: Wed, 30 Aug 2023 11:06:39 -0500 Subject: [PATCH 1/3] add comments --- source/code-snippets/crud/arrayFilters.js | 35 +++++++++++++++++++ source/code-snippets/indexes/text.js | 6 ++++ .../code-snippets/monitoring/cpm-subscribe.js | 2 ++ .../code-snippets/usage-examples/distinct.js | 9 +++-- source/code-snippets/usage-examples/find.js | 10 ++++-- .../code-snippets/usage-examples/findOne.js | 7 ++-- .../usage-examples/insertMany.js | 9 +++-- .../usage-examples/replaceOne.js | 10 ++++-- .../crud/write-operations/embedded-arrays.txt | 2 +- 9 files changed, 77 insertions(+), 13 deletions(-) diff --git a/source/code-snippets/crud/arrayFilters.js b/source/code-snippets/crud/arrayFilters.js index 818fa2028..58094afeb 100644 --- a/source/code-snippets/crud/arrayFilters.js +++ b/source/code-snippets/crud/arrayFilters.js @@ -7,9 +7,12 @@ const client = new MongoClient(uri); async function printData() { try { + + // Get the database and collection on which to run the operation const myDB = client.db("test"); const myColl = myDB.collection("testColl"); + // Print all documents console.log(JSON.stringify(await myColl.find().toArray())); } finally { await client.close(); @@ -18,18 +21,28 @@ async function printData() { async function runFirstArrayElement() { try { + + // Get the database and collection on which to run the operation const myDB = client.db("test"); const myColl = myDB.collection("testColl"); + // Print the result console.log(JSON.stringify(await myColl.find().toArray())); // start firstArrayElement example + // Query for all elements in entries array where x is a string const query = { "entries.x": { $type : "string" } }; + + // For each matched element, increase value of y by 33 const updateDocument = { $inc: { "entries.$.y": 33 } }; + + // Execute the update operation const result = await myColl.updateOne(query, updateDocument); // end firstArrayElement example + + // Print the result console.log(result.modifiedCount); console.log(JSON.stringify(await myColl.find().toArray())); } finally { @@ -39,19 +52,30 @@ async function runFirstArrayElement() { async function runAllArrayElements() { try { + + // Get the database and collection on which to run the operation const myDB = client.db("test"); const myColl = myDB.collection("testColl"); + // Print all documents console.log(JSON.stringify(await myColl.find().toArray())); // start allArrayElement example + // Query for all documents where date is May 15, 2023 const query = { date: "5/15/2023" }; + + // For each matched document, remove duration field from calls array const updateDocument = { $unset: { "calls.$[].duration": "" } }; + + // Execute the update operation const result = await myColl.updateOne(query, updateDocument); // end allArrayElement example + console.log(result.modifiedCount); + + // Print all documents console.log(JSON.stringify(await myColl.find().toArray())); } finally { await client.close(); @@ -60,16 +84,24 @@ async function runAllArrayElements() { async function arrayFiltersIdentifier() { try { + + // Get the database and collection on which to run the operation const myDB = client.db("test"); const myColl = myDB.collection("testColl"); + // Print all documents console.log(JSON.stringify(await myColl.find().toArray())); // start arrayFiltersIdentifier example + // Query for all documents where date is November 12, 2023 const query = { date: "11/12/2023" }; + + // For each matched document, change the quantity of items to 2 const updateDocument = { $mul: { "items.$[i].quantity": 2 } }; + + // Update only non-oil items used for fried rice const options = { arrayFilters: [ { @@ -78,10 +110,13 @@ async function arrayFiltersIdentifier() { } ] }; + + // Execute the update operation const result = await myColl.updateOne(query, updateDocument, options); // end arrayFiltersIdentifier example console.log(result.modifiedCount); + // Print all documents console.log(JSON.stringify(await myColl.find().toArray())); } finally { await client.close(); diff --git a/source/code-snippets/indexes/text.js b/source/code-snippets/indexes/text.js index 14c88d321..c2950e378 100644 --- a/source/code-snippets/indexes/text.js +++ b/source/code-snippets/indexes/text.js @@ -10,6 +10,7 @@ const client = new MongoClient(uri); async function run() { try { // begin-idx + // Get the database and collection on which to create the index const myDB = client.db("testDB"); const myColl = myDB.collection("blogPosts"); @@ -23,8 +24,13 @@ async function run() { console.log(`Index created: ${result}`); // begin-query + // Query for documents where body or title contain "life ahead" const query = { $text: { $search: "life ahead" } }; + + // Show only the title field const projection = { _id: 0, title: 1 }; + + // Execute the find operation const cursor = myColl.find(query).project(projection); // end-query for await (const doc of cursor) { diff --git a/source/code-snippets/monitoring/cpm-subscribe.js b/source/code-snippets/monitoring/cpm-subscribe.js index 28571f524..34ae3f525 100644 --- a/source/code-snippets/monitoring/cpm-subscribe.js +++ b/source/code-snippets/monitoring/cpm-subscribe.js @@ -9,6 +9,8 @@ const client = new MongoClient(uri); // Replace with the name of the event you are subscribing to. const eventName = ""; + +// Subscribe to the event client.on(eventName, (event) => console.log("\nreceived event:\n", event) ); diff --git a/source/code-snippets/usage-examples/distinct.js b/source/code-snippets/usage-examples/distinct.js index 5b1e2f0f6..ab25bee5b 100644 --- a/source/code-snippets/usage-examples/distinct.js +++ b/source/code-snippets/usage-examples/distinct.js @@ -7,18 +7,21 @@ const client = new MongoClient(uri); async function run() { try { - // define a database and collection on which to run the method + + // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); - // specify the document field + // Specify the document field to find distinct values for const fieldName = "year"; - // specify an optional query document + // Specify an optional query document to limit results const query = { directors: "Barbra Streisand" }; + // Execute the distinct operation const distinctValues = await movies.distinct(fieldName, query); + // Print the result console.log(distinctValues); } finally { await client.close(); diff --git a/source/code-snippets/usage-examples/find.js b/source/code-snippets/usage-examples/find.js index 2137c5d53..0486e86d2 100644 --- a/source/code-snippets/usage-examples/find.js +++ b/source/code-snippets/usage-examples/find.js @@ -7,26 +7,30 @@ const client = new MongoClient(uri); async function run() { try { + + // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); - // query for movies that have a runtime less than 15 minutes + // Query for movies that have a runtime less than 15 minutes const query = { runtime: { $lt: 15 } }; const options = { - // sort returned documents in ascending order by title (A->Z) + // Sort returned documents in ascending order by title (A->Z) sort: { title: 1 }, // Include only the `title` and `imdb` fields in each returned document projection: { _id: 0, title: 1, imdb: 1 }, }; + // Execute query const cursor = movies.find(query, options); - // print a message if no documents were found + // Print a message if no documents were found if ((await movies.countDocuments(query)) === 0) { console.log("No documents found!"); } + // Print returned documents for await (const doc of cursor) { console.dir(doc); } diff --git a/source/code-snippets/usage-examples/findOne.js b/source/code-snippets/usage-examples/findOne.js index e6aebdd2d..158b9d422 100644 --- a/source/code-snippets/usage-examples/findOne.js +++ b/source/code-snippets/usage-examples/findOne.js @@ -7,6 +7,8 @@ const client = new MongoClient(uri); async function run() { try { + + // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); @@ -14,15 +16,16 @@ async function run() { const query = { title: "The Room" }; const options = { - // sort matched documents in descending order by rating + // Sort matched documents in descending order by rating sort: { "imdb.rating": -1 }, // Include only the `title` and `imdb` fields in the returned document projection: { _id: 0, title: 1, imdb: 1 }, }; + // Execute query const movie = await movies.findOne(query, options); - // since this method returns the matched document, not a cursor, print it directly + // Since this method returns the matched document, not a cursor, print it directly console.log(movie); } finally { await client.close(); diff --git a/source/code-snippets/usage-examples/insertMany.js b/source/code-snippets/usage-examples/insertMany.js index 3b462a7ef..93725a522 100644 --- a/source/code-snippets/usage-examples/insertMany.js +++ b/source/code-snippets/usage-examples/insertMany.js @@ -7,20 +7,25 @@ const client = new MongoClient(uri); async function run() { try { + + // Get the database and collection on which to run the operation const database = client.db("insertDB"); const foods = database.collection("foods"); - // create an array of documents to insert + // Create an array of documents to insert const docs = [ { name: "cake", healthy: false }, { name: "lettuce", healthy: true }, { name: "donut", healthy: false } ]; - // this option prevents additional documents from being inserted if one fails + // Prevent additional documents from being inserted if one fails const options = { ordered: true }; + // Execute insert operation const result = await foods.insertMany(docs, options); + + // Print result console.log(`${result.insertedCount} documents were inserted`); } finally { await client.close(); diff --git a/source/code-snippets/usage-examples/replaceOne.js b/source/code-snippets/usage-examples/replaceOne.js index 854a1ba1b..7c9c9641b 100644 --- a/source/code-snippets/usage-examples/replaceOne.js +++ b/source/code-snippets/usage-examples/replaceOne.js @@ -7,17 +7,23 @@ const client = new MongoClient(uri); async function run() { try { + + // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); - // create a query for a movie to update + // Create a query to find the document to update const query = { title: { $regex: "The Cat from" } }; - // create a new document that will be used to replace the existing document + + // Create the document that will replace the existing document const replacement = { title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, }; + // Execute the replace operation const result = await movies.replaceOne(query, replacement); + + // Print the result console.log(`Modified ${result.modifiedCount} document(s)`); } finally { await client.close(); diff --git a/source/fundamentals/crud/write-operations/embedded-arrays.txt b/source/fundamentals/crud/write-operations/embedded-arrays.txt index e2d325dd4..9374d2690 100644 --- a/source/fundamentals/crud/write-operations/embedded-arrays.txt +++ b/source/fundamentals/crud/write-operations/embedded-arrays.txt @@ -283,7 +283,7 @@ code: :language: javascript :start-after: start arrayFiltersIdentifier example :end-before: end arrayFiltersIdentifier example - :emphasize-lines: 3, 6-11 + :emphasize-lines: 6, 11-16 :dedent: The update multiplied the ``quantity`` value by ``2`` for From ace91e929b8b249e6ea960330587b357b80a3b79 Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 5 Sep 2023 12:34:54 -0500 Subject: [PATCH 2/3] Apply suggestions from code review Co-authored-by: Rea Rustagi <85902999+rustagir@users.noreply.github.com> --- source/code-snippets/crud/arrayFilters.js | 10 +++++----- source/code-snippets/usage-examples/distinct.js | 2 +- source/code-snippets/usage-examples/findOne.js | 2 +- source/code-snippets/usage-examples/replaceOne.js | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/source/code-snippets/crud/arrayFilters.js b/source/code-snippets/crud/arrayFilters.js index 58094afeb..8efedae06 100644 --- a/source/code-snippets/crud/arrayFilters.js +++ b/source/code-snippets/crud/arrayFilters.js @@ -30,7 +30,7 @@ async function runFirstArrayElement() { console.log(JSON.stringify(await myColl.find().toArray())); // start firstArrayElement example - // Query for all elements in entries array where x is a string + // Query for all elements in entries array where the value of x is a string const query = { "entries.x": { $type : "string" } }; // For each matched element, increase value of y by 33 @@ -42,7 +42,7 @@ async function runFirstArrayElement() { const result = await myColl.updateOne(query, updateDocument); // end firstArrayElement example - // Print the result + // Print all documents console.log(result.modifiedCount); console.log(JSON.stringify(await myColl.find().toArray())); } finally { @@ -61,10 +61,10 @@ async function runAllArrayElements() { console.log(JSON.stringify(await myColl.find().toArray())); // start allArrayElement example - // Query for all documents where date is May 15, 2023 + // Query for all documents where date is the string "5/15/2023" const query = { date: "5/15/2023" }; - // For each matched document, remove duration field from calls array + // For each matched document, remove duration field from all entries in calls array const updateDocument = { $unset: { "calls.$[].duration": "" } }; @@ -93,7 +93,7 @@ async function arrayFiltersIdentifier() { console.log(JSON.stringify(await myColl.find().toArray())); // start arrayFiltersIdentifier example - // Query for all documents where date is November 12, 2023 + // Query for all documents where date is the string "11/12/2023" const query = { date: "11/12/2023" }; // For each matched document, change the quantity of items to 2 diff --git a/source/code-snippets/usage-examples/distinct.js b/source/code-snippets/usage-examples/distinct.js index ab25bee5b..df481ceb9 100644 --- a/source/code-snippets/usage-examples/distinct.js +++ b/source/code-snippets/usage-examples/distinct.js @@ -15,7 +15,7 @@ async function run() { // Specify the document field to find distinct values for const fieldName = "year"; - // Specify an optional query document to limit results + // Specify an optional query document to narrow results const query = { directors: "Barbra Streisand" }; // Execute the distinct operation diff --git a/source/code-snippets/usage-examples/findOne.js b/source/code-snippets/usage-examples/findOne.js index 158b9d422..2eb49a611 100644 --- a/source/code-snippets/usage-examples/findOne.js +++ b/source/code-snippets/usage-examples/findOne.js @@ -25,7 +25,7 @@ async function run() { // Execute query const movie = await movies.findOne(query, options); - // Since this method returns the matched document, not a cursor, print it directly + // Print the document returned by findOne() console.log(movie); } finally { await client.close(); diff --git a/source/code-snippets/usage-examples/replaceOne.js b/source/code-snippets/usage-examples/replaceOne.js index 7c9c9641b..340bc1845 100644 --- a/source/code-snippets/usage-examples/replaceOne.js +++ b/source/code-snippets/usage-examples/replaceOne.js @@ -12,7 +12,7 @@ async function run() { const database = client.db("sample_mflix"); const movies = database.collection("movies"); - // Create a query to find the document to update + // Create a query for documents where the title contains "The Cat from" const query = { title: { $regex: "The Cat from" } }; // Create the document that will replace the existing document From 57d6c283eab42fb152796629ecf1a523bb9585b0 Mon Sep 17 00:00:00 2001 From: Mike Woofter Date: Tue, 5 Sep 2023 12:36:12 -0500 Subject: [PATCH 3/3] rr feedback --- source/code-snippets/crud/arrayFilters.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/code-snippets/crud/arrayFilters.js b/source/code-snippets/crud/arrayFilters.js index 8efedae06..5db976727 100644 --- a/source/code-snippets/crud/arrayFilters.js +++ b/source/code-snippets/crud/arrayFilters.js @@ -33,7 +33,7 @@ async function runFirstArrayElement() { // Query for all elements in entries array where the value of x is a string const query = { "entries.x": { $type : "string" } }; - // For each matched element, increase value of y by 33 + // On first matched element, increase value of y by 33 const updateDocument = { $inc: { "entries.$.y": 33 } };