From c0b49b3280c0b7de81baa9988e016cbe825602ed Mon Sep 17 00:00:00 2001 From: Nora Reidy Date: Tue, 5 Sep 2023 11:42:43 -0400 Subject: [PATCH 1/5] DOCSP-31824: Update page titles (#774) (cherry picked from commit 9cd60b18a51817c67caf55de400fdf3692424501) --- config/redirects | 1 + source/fundamentals/crud/write-operations.txt | 4 ++-- source/fundamentals/crud/write-operations/delete.txt | 8 +++----- .../{change-a-document.txt => modify.txt} | 10 ++++------ 4 files changed, 10 insertions(+), 13 deletions(-) rename source/fundamentals/crud/write-operations/{change-a-document.txt => modify.txt} (97%) diff --git a/config/redirects b/config/redirects index 830f647ec..5277b27e1 100644 --- a/config/redirects +++ b/config/redirects @@ -21,3 +21,4 @@ raw: ${prefix}/stable -> ${base}/current/ [*-v4.2]: ${prefix}/${version}/fundamentals/utf8-validation/ -> ${base}/${version}/ [*-v5.5]: ${prefix}/${version}/fundamentals/run-command/ -> ${base}/${version}/usage-examples/command/ +[*-master]: ${prefix}/${version}/fundamentals/crud/write-operations/change-a-document/ -> ${base}/${version}/fundamentals/crud/write-operations/modify/ diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index 3d6d02c7b..3263c4a78 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -7,7 +7,7 @@ Write Operations - :doc:`/fundamentals/crud/write-operations/insert` - :doc:`/fundamentals/crud/write-operations/pkFactory` - :doc:`/fundamentals/crud/write-operations/delete` -- :doc:`/fundamentals/crud/write-operations/change-a-document` +- :doc:`/fundamentals/crud/write-operations/modify` - :doc:`/fundamentals/crud/write-operations/embedded-arrays` - :doc:`/fundamentals/crud/write-operations/upsert` @@ -17,7 +17,7 @@ Write Operations /fundamentals/crud/write-operations/insert /fundamentals/crud/write-operations/pkFactory /fundamentals/crud/write-operations/delete - /fundamentals/crud/write-operations/change-a-document + /fundamentals/crud/write-operations/modify /fundamentals/crud/write-operations/embedded-arrays /fundamentals/crud/write-operations/upsert diff --git a/source/fundamentals/crud/write-operations/delete.txt b/source/fundamentals/crud/write-operations/delete.txt index 5fe4d27cb..ead0ba2d0 100644 --- a/source/fundamentals/crud/write-operations/delete.txt +++ b/source/fundamentals/crud/write-operations/delete.txt @@ -1,10 +1,8 @@ .. _node-fundamentals-delete: -================= -Delete a Document -================= - -.. default-domain:: mongodb +================ +Delete Documents +================ .. contents:: On this page :local: diff --git a/source/fundamentals/crud/write-operations/change-a-document.txt b/source/fundamentals/crud/write-operations/modify.txt similarity index 97% rename from source/fundamentals/crud/write-operations/change-a-document.txt rename to source/fundamentals/crud/write-operations/modify.txt index 05298f6df..bf116ffcc 100644 --- a/source/fundamentals/crud/write-operations/change-a-document.txt +++ b/source/fundamentals/crud/write-operations/modify.txt @@ -1,10 +1,8 @@ .. _node-fundamentals-change-a-document: -================= -Change a Document -================= - -.. default-domain:: mongodb +================ +Modify Documents +================ .. contents:: On this page :local: @@ -15,7 +13,7 @@ Change a Document Overview -------- -You can change documents in a MongoDB collection using either **update** +You can modify documents in a MongoDB collection using either **update** or **replace** operations. Update operations mutate specified fields in one or more documents and leave other fields and values unchanged. Replace operations remove all existing fields in one or more From 8627ee1d99a1d66fde1550b778630947e8a25a57 Mon Sep 17 00:00:00 2001 From: caitlindavey Date: Wed, 30 Aug 2023 11:17:02 -0400 Subject: [PATCH 2/5] DOCSP-30081: Fix find to find() --- source/code-snippets/usage-examples/bulkWrite.js | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/source/code-snippets/usage-examples/bulkWrite.js b/source/code-snippets/usage-examples/bulkWrite.js index c89eb3f1a..4083f2c18 100644 --- a/source/code-snippets/usage-examples/bulkWrite.js +++ b/source/code-snippets/usage-examples/bulkWrite.js @@ -1,9 +1,6 @@ -/* Bulk write operation */ - -// Import MongoClient from the MongoDB node driver package const { MongoClient } = require("mongodb"); -// Replace the uri string with your MongoDB deployment's connection string +// Replace the uri string with your MongoDB deployment's connection string. const uri = ""; const client = new MongoClient(uri); @@ -13,7 +10,6 @@ async function run() { const database = client.db("sample_mflix"); const theaters = database.collection("theaters"); - // Insert a new document into the "theaters" collection const result = await theaters.bulkWrite([ { insertOne: { @@ -44,7 +40,6 @@ async function run() { }, }, { - // Update documents that match the specified filter updateMany: { filter: { "location.address.zipcode": "44011" }, update: { $set: { is_in_ohio: true } }, @@ -52,14 +47,12 @@ async function run() { }, }, { - // Delete a document that matches the specified filter deleteOne: { filter: { "location.address.street1": "221b Baker St" } }, }, ]); - // Log the result of the bulk write operation + console.log(result); } finally { - // Close the database connection when the operations are completed or if an error occurs await client.close(); } } From 6dbbab2fa6dcd115bbf0b92716ce0938245184ff Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Tue, 5 Sep 2023 14:11:42 -0500 Subject: [PATCH 3/5] docsp-32718 - add comments (#770) (cherry picked from commit 11461c34559cdc17ea0bd3717867dad6f0e1904c) --- 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..5db976727 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 the value of x is a string const query = { "entries.x": { $type : "string" } }; + + // On first 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 all documents 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 the string "5/15/2023" const query = { date: "5/15/2023" }; + + // For each matched document, remove duration field from all entries in 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 the string "11/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..df481ceb9 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 narrow 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..2eb49a611 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 + // Print the document returned by findOne() 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..340bc1845 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 for documents where the title contains "The Cat from" 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 4f1253cbc0efe9d2f66fedfb03629406d32c7930 Mon Sep 17 00:00:00 2001 From: Jordan Smith <45415425+jordan-smith721@users.noreply.github.com> Date: Tue, 5 Sep 2023 13:37:46 -0700 Subject: [PATCH 4/5] Added code comments (#772) (#778) (cherry picked from commit 5b0652a7a3338f73731150eed574a39fa2320b7c) --- source/code-snippets/crud/startrek.js | 35 ++++++++++++------- .../code-snippets/monitoring/apm-subscribe.js | 16 +++++---- .../code-snippets/monitoring/cpm-subscribe.js | 5 ++- .../monitoring/sdam-subscribe.js | 16 +++++---- .../usage-examples/changeStream_listener.js | 18 ++++++---- .../code-snippets/usage-examples/command.js | 9 +++-- .../usage-examples/updateMany.js | 11 ++++-- .../usage-examples/updateMany.ts | 7 ++++ 8 files changed, 77 insertions(+), 40 deletions(-) diff --git a/source/code-snippets/crud/startrek.js b/source/code-snippets/crud/startrek.js index a2a283b5d..96eae6d42 100644 --- a/source/code-snippets/crud/startrek.js +++ b/source/code-snippets/crud/startrek.js @@ -1,12 +1,14 @@ +/* Text search */ + const { MongoClient } = require("mongodb"); -// Replace the following string with your MongoDB deployment's connection string. -const uri = - "mongodb+srv://:@?writeConcern=majority"; +// Replace the following string with your MongoDB deployment's connection string +const uri = "mongodb+srv://:@?writeConcern=majority"; const client = new MongoClient(uri); async function word(movies) { // start word text example + // Create a query that searches for the string "trek" const query = { $text: { $search: "trek" } }; // Return only the `title` of each matched document @@ -15,14 +17,15 @@ async function word(movies) { title: 1, }; - // find documents based on our query and projection + // Find documents based on our query and projection const cursor = movies.find(query).project(projection); // end word text example - // 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 all documents that were found for await (const doc of cursor) { console.dir(doc); } @@ -30,6 +33,7 @@ async function word(movies) { async function phrase(movies) { // start phrase text example + // Create a query that searches for the phrase "star trek" const query = { $text: { $search: "\"star trek\"" } }; // Return only the `title` of each matched document @@ -38,14 +42,15 @@ async function phrase(movies) { title: 1, }; - // find documents based on our query and projection + // Find documents based on the query and projection const cursor = movies.find(query).project(projection); // end phrase text example - // 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 all documents that were found for await (const doc of cursor) { console.dir(doc); } @@ -53,6 +58,7 @@ async function phrase(movies) { async function negation(movies) { // start negation text example + // Create a query that searches for the phrase "star trek" while omitting "into darkness" const query = { $text: { $search: "\"star trek\" -\"into darkness\"" } }; // Include only the `title` field of each matched document @@ -61,14 +67,15 @@ async function negation(movies) { title: 1, }; - // find documents based on our query and projection + // Find documents based on the query and projection const cursor = movies.find(query).project(projection); // end negation text example - // 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 all documents that were found for await (const doc of cursor) { console.dir(doc); } @@ -76,10 +83,12 @@ async function negation(movies) { async function relevance(movies) { // start relevance text example + // Create a query that searches for the phrase "star trek" while omitting "into darkness"r const query = { $text: { $search: "\"star trek\" -\"into darkness\"" } }; - // sort returned documents by descending text relevance score + // Sort returned documents by descending text relevance score const sort = { score: { $meta: "textScore" } }; + // Include only the `title` and `score` fields in each returned document const projection = { _id: 0, @@ -87,17 +96,18 @@ async function relevance(movies) { score: { $meta: "textScore" }, }; - // find documents based on our query, sort, and projection + // Find documents based on the query, sort, and projection const cursor = movies .find(query) .sort(sort) .project(projection); // end relevance text example - // 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 all documents that were found for await (const doc of cursor) { console.dir(doc); } @@ -113,6 +123,7 @@ async function run() { await negation(movies); await relevance(movies); } finally { + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/monitoring/apm-subscribe.js b/source/code-snippets/monitoring/apm-subscribe.js index 8f165d9c2..10251165c 100644 --- a/source/code-snippets/monitoring/apm-subscribe.js +++ b/source/code-snippets/monitoring/apm-subscribe.js @@ -1,25 +1,27 @@ +/* Subscribe to an event */ + const { MongoClient } = require("mongodb"); -// Replace the following with your MongoDB deployment's connection -// string. -const uri = - "mongodb+srv:///?replicaSet=rs&writeConcern=majority"; +// Replace the following with your MongoDB deployment's connection string +const uri = "mongodb+srv:///?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri, { monitorCommands:true }); -// Replace with the name of the event you are subscribing to. +// Replace with the name of the event you are subscribing to const eventName = ""; + +// Subscribe to a specified event and print a message when the event is received client.on(eventName, event => { console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`); }); async function run() { try { - // Establish and verify connection + // Establish and verify connection to the "admin" database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { - // Ensures that the client will close when you finish/error + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/monitoring/cpm-subscribe.js b/source/code-snippets/monitoring/cpm-subscribe.js index 34ae3f525..596af4178 100644 --- a/source/code-snippets/monitoring/cpm-subscribe.js +++ b/source/code-snippets/monitoring/cpm-subscribe.js @@ -1,13 +1,12 @@ const { MongoClient } = require("mongodb"); -// Replace the following with your MongoDB deployment's connection -// string. +// Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv:///?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); -// Replace with the name of the event you are subscribing to. +// Replace with the name of the event you are subscribing to const eventName = ""; // Subscribe to the event diff --git a/source/code-snippets/monitoring/sdam-subscribe.js b/source/code-snippets/monitoring/sdam-subscribe.js index 314eca0a8..90db667f1 100644 --- a/source/code-snippets/monitoring/sdam-subscribe.js +++ b/source/code-snippets/monitoring/sdam-subscribe.js @@ -1,25 +1,27 @@ +/* Subscribe to SDAM event */ + const { MongoClient } = require("mongodb"); -// Replace the following with your MongoDB deployment's connection -// string. -const uri = - "mongodb+srv:///?replicaSet=rs&writeConcern=majority"; +// Replace the following with your MongoDB deployment's connection string +const uri = "mongodb+srv:///?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); -// Replace with the name of the event you are subscribing to. +// Replace with the name of the event you are subscribing to const eventName = ""; + +// Subscribe to a specified event and print a message when the event is received client.on(eventName, event => { console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`); }); async function run() { try { - // Establish and verify connection + // Establish and verify connection to the database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { - // Ensures that the client will close when you finish/error + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/usage-examples/changeStream_listener.js b/source/code-snippets/usage-examples/changeStream_listener.js index 7d6499042..dea0dd170 100644 --- a/source/code-snippets/usage-examples/changeStream_listener.js +++ b/source/code-snippets/usage-examples/changeStream_listener.js @@ -1,6 +1,8 @@ +/* Change stream listener */ + import { MongoClient } from "mongodb"; -// Replace the uri string with your MongoDB deployment's connection string. +// Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); @@ -16,28 +18,32 @@ async function run() { const database = client.db("insertDB"); const haikus = database.collection("haikus"); - // open a Change Stream on the "haikus" collection + // Open a Change Stream on the "haikus" collection changeStream = haikus.watch(); - // set up a listener when change events are emitted + // Set up a change stream listener when change events are emitted changeStream.on("change", next => { - // process any change event + // Print any change event console.log("received a change to the collection: \t", next); }); + // Pause before inserting a document await simulateAsyncPause(); + // Insert a new document into the collection await myColl.insertOne({ title: "Record of a Shriveled Datum", content: "No bytes, no problem. Just insert a document, in MongoDB", }); + // Pause before closing the change stream await simulateAsyncPause(); - await changeStream.close(); - + // Close the change stream and print a message to the console when it is closed + await changeStream.close(); console.log("closed the change stream"); } finally { + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/usage-examples/command.js b/source/code-snippets/usage-examples/command.js index 4fadb623f..b1fe5203b 100644 --- a/source/code-snippets/usage-examples/command.js +++ b/source/code-snippets/usage-examples/command.js @@ -1,19 +1,24 @@ +/* Run a database command */ + import { MongoClient } from "mongodb"; -// Replace the uri string with your MongoDB deployment's connection string. +// Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); async function run() { try { + // Get the "sample_mflix" database const db = client.db("sample_mflix"); - // find the storage statistics for the "sample_mflix" database using the 'dbStats' command + + // Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command const result = await db.command({ dbStats: 1, }); console.log(result); } finally { + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/usage-examples/updateMany.js b/source/code-snippets/usage-examples/updateMany.js index cb4c7d2da..8ad4e1c88 100644 --- a/source/code-snippets/usage-examples/updateMany.js +++ b/source/code-snippets/usage-examples/updateMany.js @@ -1,19 +1,22 @@ +/* Update multiple documents */ + import { MongoClient } from "mongodb"; -// Replace the uri string with your MongoDB deployment's connection string. +// Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); async function run() { try { + // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection("movies"); - // create a filter to update all movies with a 'G' rating + // Create a filter to update all movies with a 'G' rating const filter = { rated: "G" }; - // increment every document matching the filter with 2 more comments + // Create an update document specifying the change to make const updateDoc = { $set: { random_review: `After viewing I am ${ @@ -21,9 +24,11 @@ async function run() { }% more satisfied with life.`, }, }; + // Update the documents that match the specified filter const result = await movies.updateMany(filter, updateDoc); console.log(`Updated ${result.modifiedCount} documents`); } finally { + // Close the database connection on completion or error await client.close(); } } diff --git a/source/code-snippets/usage-examples/updateMany.ts b/source/code-snippets/usage-examples/updateMany.ts index f599c9dfe..e02a8eb21 100644 --- a/source/code-snippets/usage-examples/updateMany.ts +++ b/source/code-snippets/usage-examples/updateMany.ts @@ -1,3 +1,5 @@ +/* Update multiple documents */ + import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string. @@ -13,6 +15,7 @@ enum Rating { NR = "NOT RATED", } +// Create a Movie interface interface Movie { rated: Rating; random_review?: string; @@ -20,8 +23,11 @@ interface Movie { async function run() { try { + // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection("movies"); + + // Update all documents that match the specified filter const result = await movies.updateMany( { rated: Rating.G }, { @@ -34,6 +40,7 @@ async function run() { ); console.log(`Updated ${result.modifiedCount} documents`); } finally { + // Close the database connection on completion or error await client.close(); } } From 49f891eba82085ff3dbba84707896fd58595eca2 Mon Sep 17 00:00:00 2001 From: caitlindavey Date: Mon, 18 Nov 2024 16:07:54 -0500 Subject: [PATCH 5/5] Fixing nested components --- source/faq.txt | 8 +++----- source/fundamentals/run-command.txt | 6 ++---- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/source/faq.txt b/source/faq.txt index 9a627c064..49e8bf0e6 100644 --- a/source/faq.txt +++ b/source/faq.txt @@ -123,11 +123,9 @@ What Is the Difference Between "connectTimeoutMS", "socketTimeoutMS" and "maxTim for an individual connection from your connection pool to establish a TCP connection to the {+mdb-server+} before timing out. - - .. tip:: - - To modify the allowed time for `MongoClient.connect <{+api+}/classes/MongoClient.html#connect>`__ to establish a - connection to a {+mdb-server+}, use the ``serverSelectionTimeoutMS`` option instead. + + To modify the allowed time for `MongoClient.connect <{+api+}/classes/MongoClient.html#connect>`__ to establish a + connection to a {+mdb-server+}, use the ``serverSelectionTimeoutMS`` option instead. **Default:** 30000 * - **socketTimeoutMS** diff --git a/source/fundamentals/run-command.txt b/source/fundamentals/run-command.txt index c5609adb1..b8b80f4bf 100644 --- a/source/fundamentals/run-command.txt +++ b/source/fundamentals/run-command.txt @@ -143,10 +143,8 @@ with the following fields: - Indicates the logical time of the operation. MongoDB uses the logical time to order operations. - .. seealso:: - - To learn more about logical time, see our :website:`blog post about - the Global Logical Clock `. + To learn more about logical time, see our :website:`blog post about + the Global Logical Clock `. * - ``$clusterTime`` - Provides a document that returns the signed cluster time. Cluster time is a