Skip to content

Commit 5b0652a

Browse files
Added code comments (#772)
1 parent f751b1b commit 5b0652a

File tree

8 files changed

+77
-40
lines changed

8 files changed

+77
-40
lines changed

source/code-snippets/crud/startrek.js

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
/* Text search */
2+
13
const { MongoClient } = require("mongodb");
24

3-
// Replace the following string with your MongoDB deployment's connection string.
4-
const uri =
5-
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
5+
// Replace the following string with your MongoDB deployment's connection string
6+
const uri = "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
67
const client = new MongoClient(uri);
78

89
async function word(movies) {
910
// start word text example
11+
// Create a query that searches for the string "trek"
1012
const query = { $text: { $search: "trek" } };
1113

1214
// Return only the `title` of each matched document
@@ -15,21 +17,23 @@ async function word(movies) {
1517
title: 1,
1618
};
1719

18-
// find documents based on our query and projection
20+
// Find documents based on our query and projection
1921
const cursor = movies.find(query).project(projection);
2022
// end word text example
2123

22-
// print a message if no documents were found
24+
// Print a message if no documents were found
2325
if ((await movies.countDocuments(query)) === 0) {
2426
console.log("No documents found!");
2527
}
28+
// Print all documents that were found
2629
for await (const doc of cursor) {
2730
console.dir(doc);
2831
}
2932
}
3033

3134
async function phrase(movies) {
3235
// start phrase text example
36+
// Create a query that searches for the phrase "star trek"
3337
const query = { $text: { $search: "\"star trek\"" } };
3438

3539
// Return only the `title` of each matched document
@@ -38,21 +42,23 @@ async function phrase(movies) {
3842
title: 1,
3943
};
4044

41-
// find documents based on our query and projection
45+
// Find documents based on the query and projection
4246
const cursor = movies.find(query).project(projection);
4347
// end phrase text example
4448

45-
// print a message if no documents were found
49+
// Print a message if no documents were found
4650
if ((await movies.countDocuments(query)) === 0) {
4751
console.log("No documents found!");
4852
}
53+
// Print all documents that were found
4954
for await (const doc of cursor) {
5055
console.dir(doc);
5156
}
5257
}
5358

5459
async function negation(movies) {
5560
// start negation text example
61+
// Create a query that searches for the phrase "star trek" while omitting "into darkness"
5662
const query = { $text: { $search: "\"star trek\" -\"into darkness\"" } };
5763

5864
// Include only the `title` field of each matched document
@@ -61,43 +67,47 @@ async function negation(movies) {
6167
title: 1,
6268
};
6369

64-
// find documents based on our query and projection
70+
// Find documents based on the query and projection
6571
const cursor = movies.find(query).project(projection);
6672
// end negation text example
6773

68-
// print a message if no documents were found
74+
// Print a message if no documents were found
6975
if ((await movies.countDocuments(query)) === 0) {
7076
console.log("No documents found!");
7177
}
78+
// Print all documents that were found
7279
for await (const doc of cursor) {
7380
console.dir(doc);
7481
}
7582
}
7683

7784
async function relevance(movies) {
7885
// start relevance text example
86+
// Create a query that searches for the phrase "star trek" while omitting "into darkness"r
7987
const query = { $text: { $search: "\"star trek\" -\"into darkness\"" } };
8088

81-
// sort returned documents by descending text relevance score
89+
// Sort returned documents by descending text relevance score
8290
const sort = { score: { $meta: "textScore" } };
91+
8392
// Include only the `title` and `score` fields in each returned document
8493
const projection = {
8594
_id: 0,
8695
title: 1,
8796
score: { $meta: "textScore" },
8897
};
8998

90-
// find documents based on our query, sort, and projection
99+
// Find documents based on the query, sort, and projection
91100
const cursor = movies
92101
.find(query)
93102
.sort(sort)
94103
.project(projection);
95104
// end relevance text example
96105

97-
// print a message if no documents were found
106+
// Print a message if no documents were found
98107
if ((await movies.countDocuments(query)) === 0) {
99108
console.log("No documents found!");
100109
}
110+
// Print all documents that were found
101111
for await (const doc of cursor) {
102112
console.dir(doc);
103113
}
@@ -113,6 +123,7 @@ async function run() {
113123
await negation(movies);
114124
await relevance(movies);
115125
} finally {
126+
// Close the database connection on completion or error
116127
await client.close();
117128
}
118129
}

source/code-snippets/monitoring/apm-subscribe.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
1+
/* Subscribe to an event */
2+
13
const { MongoClient } = require("mongodb");
24

3-
// Replace the following with your MongoDB deployment's connection
4-
// string.
5-
const uri =
6-
"mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
5+
// Replace the following with your MongoDB deployment's connection string
6+
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
77

88
const client = new MongoClient(uri, { monitorCommands:true });
99

10-
// Replace <event name> with the name of the event you are subscribing to.
10+
// Replace <event name> with the name of the event you are subscribing to
1111
const eventName = "<event name>";
12+
13+
// Subscribe to a specified event and print a message when the event is received
1214
client.on(eventName, event => {
1315
console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
1416
});
1517

1618
async function run() {
1719
try {
18-
// Establish and verify connection
20+
// Establish and verify connection to the "admin" database
1921
await client.db("admin").command({ ping: 1 });
2022
console.log("Connected successfully");
2123
} finally {
22-
// Ensures that the client will close when you finish/error
24+
// Close the database connection on completion or error
2325
await client.close();
2426
}
2527
}

source/code-snippets/monitoring/cpm-subscribe.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
const { MongoClient } = require("mongodb");
22

3-
// Replace the following with your MongoDB deployment's connection
4-
// string.
3+
// Replace the following with your MongoDB deployment's connection string
54
const uri =
65
"mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
76

87
const client = new MongoClient(uri);
98

10-
// Replace <event name> with the name of the event you are subscribing to.
9+
// Replace <event name> with the name of the event you are subscribing to
1110
const eventName = "<event name>";
1211
client.on(eventName, (event) =>
1312
console.log("\nreceived event:\n", event)

source/code-snippets/monitoring/sdam-subscribe.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
1+
/* Subscribe to SDAM event */
2+
13
const { MongoClient } = require("mongodb");
24

3-
// Replace the following with your MongoDB deployment's connection
4-
// string.
5-
const uri =
6-
"mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
5+
// Replace the following with your MongoDB deployment's connection string
6+
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
77

88
const client = new MongoClient(uri);
99

10-
// Replace <event name> with the name of the event you are subscribing to.
10+
// Replace <event name> with the name of the event you are subscribing to
1111
const eventName = "<event name>";
12+
13+
// Subscribe to a specified event and print a message when the event is received
1214
client.on(eventName, event => {
1315
console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
1416
});
1517

1618
async function run() {
1719
try {
18-
// Establish and verify connection
20+
// Establish and verify connection to the database
1921
await client.db("admin").command({ ping: 1 });
2022
console.log("Connected successfully");
2123
} finally {
22-
// Ensures that the client will close when you finish/error
24+
// Close the database connection on completion or error
2325
await client.close();
2426
}
2527
}

source/code-snippets/usage-examples/changeStream_listener.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
/* Change stream listener */
2+
13
import { MongoClient } from "mongodb";
24

3-
// Replace the uri string with your MongoDB deployment's connection string.
5+
// Replace the uri string with your MongoDB deployment's connection string
46
const uri = "<connection string uri>";
57

68
const client = new MongoClient(uri);
@@ -16,28 +18,32 @@ async function run() {
1618
const database = client.db("insertDB");
1719
const haikus = database.collection("haikus");
1820

19-
// open a Change Stream on the "haikus" collection
21+
// Open a Change Stream on the "haikus" collection
2022
changeStream = haikus.watch();
2123

22-
// set up a listener when change events are emitted
24+
// Set up a change stream listener when change events are emitted
2325
changeStream.on("change", next => {
24-
// process any change event
26+
// Print any change event
2527
console.log("received a change to the collection: \t", next);
2628
});
2729

30+
// Pause before inserting a document
2831
await simulateAsyncPause();
2932

33+
// Insert a new document into the collection
3034
await myColl.insertOne({
3135
title: "Record of a Shriveled Datum",
3236
content: "No bytes, no problem. Just insert a document, in MongoDB",
3337
});
3438

39+
// Pause before closing the change stream
3540
await simulateAsyncPause();
3641

37-
await changeStream.close();
38-
42+
// Close the change stream and print a message to the console when it is closed
43+
await changeStream.close();
3944
console.log("closed the change stream");
4045
} finally {
46+
// Close the database connection on completion or error
4147
await client.close();
4248
}
4349
}

source/code-snippets/usage-examples/command.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
1+
/* Run a database command */
2+
13
import { MongoClient } from "mongodb";
24

3-
// Replace the uri string with your MongoDB deployment's connection string.
5+
// Replace the uri string with your MongoDB deployment's connection string
46
const uri = "<connection string uri>";
57

68
const client = new MongoClient(uri);
79

810
async function run() {
911
try {
12+
// Get the "sample_mflix" database
1013
const db = client.db("sample_mflix");
11-
// find the storage statistics for the "sample_mflix" database using the 'dbStats' command
14+
15+
// Find and print the storage statistics for the "sample_mflix" database using the 'dbStats' command
1216
const result = await db.command({
1317
dbStats: 1,
1418
});
1519
console.log(result);
1620
} finally {
21+
// Close the database connection on completion or error
1722
await client.close();
1823
}
1924
}

source/code-snippets/usage-examples/updateMany.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,34 @@
1+
/* Update multiple documents */
2+
13
import { MongoClient } from "mongodb";
24

3-
// Replace the uri string with your MongoDB deployment's connection string.
5+
// Replace the uri string with your MongoDB deployment's connection string
46
const uri = "<connection string uri>";
57

68
const client = new MongoClient(uri);
79

810
async function run() {
911
try {
12+
// Get the "movies" collection in the "sample_mflix" database
1013
const database = client.db("sample_mflix");
1114
const movies = database.collection("movies");
1215

13-
// create a filter to update all movies with a 'G' rating
16+
// Create a filter to update all movies with a 'G' rating
1417
const filter = { rated: "G" };
1518

16-
// increment every document matching the filter with 2 more comments
19+
// Create an update document specifying the change to make
1720
const updateDoc = {
1821
$set: {
1922
random_review: `After viewing I am ${
2023
100 * Math.random()
2124
}% more satisfied with life.`,
2225
},
2326
};
27+
// Update the documents that match the specified filter
2428
const result = await movies.updateMany(filter, updateDoc);
2529
console.log(`Updated ${result.modifiedCount} documents`);
2630
} finally {
31+
// Close the database connection on completion or error
2732
await client.close();
2833
}
2934
}

source/code-snippets/usage-examples/updateMany.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/* Update multiple documents */
2+
13
import { MongoClient } from "mongodb";
24

35
// Replace the uri string with your MongoDB deployment's connection string.
@@ -13,15 +15,19 @@ enum Rating {
1315
NR = "NOT RATED",
1416
}
1517

18+
// Create a Movie interface
1619
interface Movie {
1720
rated: Rating;
1821
random_review?: string;
1922
}
2023

2124
async function run() {
2225
try {
26+
// Get the "movies" collection in the "sample_mflix" database
2327
const database = client.db("sample_mflix");
2428
const movies = database.collection<Movie>("movies");
29+
30+
// Update all documents that match the specified filter
2531
const result = await movies.updateMany(
2632
{ rated: Rating.G },
2733
{
@@ -34,6 +40,7 @@ async function run() {
3440
);
3541
console.log(`Updated ${result.modifiedCount} documents`);
3642
} finally {
43+
// Close the database connection on completion or error
3744
await client.close();
3845
}
3946
}

0 commit comments

Comments
 (0)