Skip to content

Added code comments (#772) #778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions source/code-snippets/crud/startrek.js
Original file line number Diff line number Diff line change
@@ -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://<user>:<password>@<cluster-url>?writeConcern=majority";
// Replace the following string with your MongoDB deployment's connection string
const uri = "mongodb+srv://<user>:<password>@<cluster-url>?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
Expand All @@ -15,21 +17,23 @@ 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);
}
}

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
Expand All @@ -38,21 +42,23 @@ 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);
}
}

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
Expand All @@ -61,43 +67,47 @@ 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);
}
}

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,
title: 1,
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);
}
Expand All @@ -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();
}
}
Expand Down
16 changes: 9 additions & 7 deletions source/code-snippets/monitoring/apm-subscribe.js
Original file line number Diff line number Diff line change
@@ -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://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
// Replace the following with your MongoDB deployment's connection string
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";

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

// Replace <event name> with the name of the event you are subscribing to.
// Replace <event name> with the name of the event you are subscribing to
const eventName = "<event name>";

// 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();
}
}
Expand Down
5 changes: 2 additions & 3 deletions source/code-snippets/monitoring/cpm-subscribe.js
Original file line number Diff line number Diff line change
@@ -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://<clusterUrl>/?replicaSet=rs&writeConcern=majority";

const client = new MongoClient(uri);

// Replace <event name> with the name of the event you are subscribing to.
// Replace <event name> with the name of the event you are subscribing to
const eventName = "<event name>";

// Subscribe to the event
Expand Down
16 changes: 9 additions & 7 deletions source/code-snippets/monitoring/sdam-subscribe.js
Original file line number Diff line number Diff line change
@@ -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://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
// Replace the following with your MongoDB deployment's connection string
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";

const client = new MongoClient(uri);

// Replace <event name> with the name of the event you are subscribing to.
// Replace <event name> with the name of the event you are subscribing to
const eventName = "<event name>";

// 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();
}
}
Expand Down
18 changes: 12 additions & 6 deletions source/code-snippets/usage-examples/changeStream_listener.js
Original file line number Diff line number Diff line change
@@ -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 = "<connection string uri>";

const client = new MongoClient(uri);
Expand All @@ -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();
}
}
Expand Down
9 changes: 7 additions & 2 deletions source/code-snippets/usage-examples/command.js
Original file line number Diff line number Diff line change
@@ -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 = "<connection string 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();
}
}
Expand Down
11 changes: 8 additions & 3 deletions source/code-snippets/usage-examples/updateMany.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
/* 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 = "<connection string 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 ${
100 * Math.random()
}% 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();
}
}
Expand Down
7 changes: 7 additions & 0 deletions source/code-snippets/usage-examples/updateMany.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* Update multiple documents */

import { MongoClient } from "mongodb";

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

// Create a Movie interface
interface Movie {
rated: Rating;
random_review?: string;
}

async function run() {
try {
// Get the "movies" collection in the "sample_mflix" database
const database = client.db("sample_mflix");
const movies = database.collection<Movie>("movies");

// Update all documents that match the specified filter
const result = await movies.updateMany(
{ rated: Rating.G },
{
Expand All @@ -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();
}
}
Expand Down