Skip to content
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

docsp-32718 - add comments #770

Merged
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: 35 additions & 0 deletions source/code-snippets/crud/arrayFilters.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ const client = new MongoClient(uri);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: I thought we were supposed to add code comments for the import statement and client creation as well -- Up to you if you want to add to the files throughout this PR.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw those in the chat gpt example, but thought they were more like "this is a stop sign" than anything substantial.

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();
Expand All @@ -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 {
Expand All @@ -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();
Expand All @@ -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: [
{
Expand All @@ -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();
Expand Down
6 changes: 6 additions & 0 deletions source/code-snippets/indexes/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand All @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions source/code-snippets/monitoring/cpm-subscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const client = new MongoClient(uri);

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

// Subscribe to the event
client.on(eventName, (event) =>
console.log("\nreceived event:\n", event)
);
Expand Down
9 changes: 6 additions & 3 deletions source/code-snippets/usage-examples/distinct.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
10 changes: 7 additions & 3 deletions source/code-snippets/usage-examples/find.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,30 @@ const client = new MongoClient(uri);

async function run() {
try {
Comment on lines 8 to 9
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: for the Usage examples that have JS and TS versions, should we update both?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caitlin confirmed JS only


// 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);
}
Expand Down
7 changes: 5 additions & 2 deletions source/code-snippets/usage-examples/findOne.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +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("sample_mflix");
const movies = database.collection("movies");

// Query for a movie that has the title 'The Room'
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();
Expand Down
9 changes: 7 additions & 2 deletions source/code-snippets/usage-examples/insertMany.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
10 changes: 8 additions & 2 deletions source/code-snippets/usage-examples/replaceOne.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down