Skip to content

Commit b67bac8

Browse files
caitlindaveyrustagir
authored andcommitted
Docsp 32718 code whisperer indexes (mongodb#773)
* Bulk Write Snippet Update * Bulk Write Snippet Update * Code comments added to files to describe code * Adding code comments to index files * Fixes to get rid of errors in previous build related to start/end of code examples * updated comments to follow agreed convention * Update source/code-snippets/crud/cursor.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/crud/cursor.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/crud/cursor.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/crud/cursor.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/crud/cursor.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/usage-examples/changeStream.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/usage-examples/changeStream.js Co-authored-by: Rea Rustagi <[email protected]> * Update source/code-snippets/usage-examples/bulkWrite.js Co-authored-by: Rea Rustagi <[email protected]> --------- Co-authored-by: Rea Rustagi <[email protected]>
1 parent 2541981 commit b67bac8

File tree

8 files changed

+51
-34
lines changed

8 files changed

+51
-34
lines changed

source/code-snippets/crud/cursor.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
// Cursor-based document retrieval
12
const { MongoClient } = require("mongodb");
23
const stream = require("stream");
34

4-
// Replace the following string with your MongoDB deployment's connection string.
5+
// Replace the following string with your MongoDB deployment's connection string
56
const uri =
67
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
78
const client = new MongoClient(uri);
8-
9+
// Asynchronous iteration by using cursor methods
910
async function asyncIteration(myColl) {
1011
// start async cursor example
1112
const cursor = myColl.find({});
@@ -15,7 +16,7 @@ async function asyncIteration(myColl) {
1516
}
1617
// end async cursor example
1718
}
18-
19+
// Manual iteration using cursor methods
1920
async function manualIteration(myColl) {
2021
// start manual cursor example
2122
const cursor = myColl.find({});
@@ -25,30 +26,30 @@ async function manualIteration(myColl) {
2526
}
2627
// end manual cursor example
2728
}
28-
29+
// Stream documents
2930
async function streamAPI(myColl) {
3031
// start stream cursor example
3132
const cursor = myColl.find({});
3233
cursor.stream().on("data", doc => console.log(doc));
3334
// end stream cursor example
3435
}
35-
36+
// Event-based iteration using cursor events
3637
async function eventAPI(myColl) {
3738
// start event cursor example
3839
const cursor = myColl.find({});
3940
// the "data" event is fired once per document
4041
cursor.on("data", data => console.log(data));
4142
// end event cursor example
4243
}
43-
44+
// Fetch all documents as an array using the toArray method
4445
async function fetchAll(myColl) {
4546
// start fetchAll cursor example
4647
const cursor = myColl.find({});
4748
const allValues = await cursor.toArray();
4849
// end fetchAll cursor example
4950
console.log(allValues.length);
5051
}
51-
52+
// Rewind the cursor
5253
async function rewind(myColl) {
5354
// start rewind cursor example
5455
const cursor = myColl.find({});
@@ -59,7 +60,7 @@ async function rewind(myColl) {
5960
console.log("Second count: " + secondResult.length);
6061
// end rewind cursor example
6162
}
62-
63+
// Close a cursor
6364
async function close(myColl) {
6465
const cursor = myColl.find({});
6566

source/code-snippets/crud/pizza.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// CRUD (Create, Read, Update, Delete) operations
12
const { MongoClient } = require("mongodb");
23

34
// Replace the following string with your MongoDB deployment's connection string.
@@ -13,8 +14,8 @@ async function run() {
1314
try {
1415
const database = client.db("test");
1516
const orders = database.collection("orders");
16-
1717
// start find crud example
18+
// Search for orders by name and within a specific date range
1819
const findResult = await orders.find({
1920
name: "Lemony Snicket",
2021
date: {
@@ -24,8 +25,8 @@ async function run() {
2425
});
2526
// end find crud example
2627
console.log(await findResult.toArray());
27-
2828
// start aggregate crud example
29+
// Group orders by status within the last week
2930
const aggregateResult = await orders.aggregate([
3031
{
3132
$match: {
@@ -46,8 +47,8 @@ async function run() {
4647
]);
4748
// end aggregate crud example
4849
console.log(await aggregateResult.toArray());
49-
5050
// start watch crud example
51+
// Set up a change stream to listen for new order insertions
5152
const changeStream = orders.watch([
5253
{ $match: { operationType: "insert" } },
5354
{
@@ -63,10 +64,10 @@ async function run() {
6364
});
6465
// end watch crud example
6566

66-
// force change stream to instantiate so it can see the insert
67+
// Allow the change stream to instantiate so it can see the insert
6768
await sleep(1);
68-
6969
// start insert crud example
70+
// Insert a new order document
7071
const insertResult = await orders.insertOne({
7172
date: new Date(Date.now()),
7273
address: "667 Dark Avenue, San Francisco, CA, 94110",
@@ -89,8 +90,8 @@ async function run() {
8990
});
9091
// end insert crud example
9192
console.log(insertResult.insertedCount); // should be 1
92-
9393
// start update crud example
94+
// Update an existing order's address
9495
const updateResult = await orders.updateOne(
9596
{
9697
address: "667 Dark Avenue, San Francisco, CA, 94110",
@@ -103,8 +104,8 @@ async function run() {
103104
);
104105
// end update crud example
105106
console.log(updateResult.modifiedCount); // should be 1
106-
107107
// start delete crud example
108+
// Delete an order document based on specified conditions
108109
const deleteResult = await orders.deleteOne({
109110
address: "13 Lousy Lane",
110111
name: "Violet Baudelaire",
@@ -115,7 +116,7 @@ async function run() {
115116
});
116117
// end delete crud example
117118
console.log(deleteResult.deletedCount); // should be 0
118-
119+
// Close the change stream and client connection
119120
await changeStream.close();
120121
} finally {
121122
await client.close();

source/code-snippets/crud/theaters.js

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
// Geospatial queries using proximity to a location and a specific geographic range
12
const { MongoClient } = require("mongodb");
23

34
// Replace the following string with your MongoDB deployment's connection string.
45
const uri =
56
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
67
const client = new MongoClient(uri);
7-
8+
// start proximity geo example
9+
// Find theaters within a certain proximity
810
async function proximity(theaters) {
9-
// start proximity geo example
11+
// Define the query to find theaters near a specific location
1012
const query = {
1113
"location.geo": {
1214
$near: {
@@ -15,30 +17,31 @@ async function proximity(theaters) {
1517
},
1618
},
1719
};
18-
19-
// find documents based on our query
20+
// Find documents based on our query
2021
const cursor = theaters.find(query);
2122
// end proximity geo example
2223

23-
// print a message if no documents were found
24+
// Print a message if no documents were found
2425
if ((await theaters.countDocuments(query)) === 0) {
2526
console.log("No documents found!");
2627
}
28+
// Iterate through the found documents and display them
2729
for await (const doc of cursor) {
2830
console.dir(doc);
2931
}
3032
}
31-
33+
// start range geo example
34+
// Find theaters within a specific geographic range
3235
async function range(theaters) {
33-
// start range geo example
36+
// Define the query to find theaters within a specified polygon
3437
const query = {
3538
"location.geo": {
3639
$geoWithin: {
3740
$geometry: {
3841
type: "Polygon",
3942
coordinates: [
4043
[
41-
[-72, 40],
44+
[-72, 40], // Polygon coordinates defining the range
4245
[-74, 41],
4346
[-72, 39],
4447
[-72, 40],
@@ -49,14 +52,15 @@ async function range(theaters) {
4952
},
5053
};
5154

52-
// find documents based on our query
55+
// Find documents based on our query
5356
const cursor = theaters.find(query);
5457
// end range geo example
5558

56-
// print a message if no documents were found
59+
// Print a message if no documents were found
5760
if ((await theaters.countDocuments(query)) === 0) {
5861
console.log("No documents found!");
5962
}
63+
// Iterate through the found documents and display them
6064
for await (const doc of cursor) {
6165
console.dir(doc);
6266
}

source/code-snippets/indexes/searchIndexes.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
// Search Index operations
12
const { MongoClient } = require("mongodb");
23

3-
// Replace the following with your MongoDB deployment's connection
4-
// string.
4+
// Replace the following with your MongoDB deployment's connection string
55
const uri =
66
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
77

@@ -17,6 +17,7 @@ async function run() {
1717
const collection = database.collection("<collectionName>");
1818

1919
// start createSearchIndex example
20+
// Create a search index
2021
const index1 = {
2122
name: "search1",
2223
definition: {
@@ -29,6 +30,7 @@ async function run() {
2930
// end createSearchIndex example
3031

3132
// start listSearchIndexes example
33+
// List search indexes
3234
const result = await collection.listSearchIndexes().toArray();
3335
console.log("Existing search indexes:\n");
3436
for (const doc in result) {
@@ -37,6 +39,7 @@ async function run() {
3739
// end listSearchIndexes example
3840

3941
// start updateSearchIndex example
42+
// Update a search index
4043
const index2 = {
4144
"mappings": {
4245
"dynamic": true,
@@ -51,6 +54,7 @@ async function run() {
5154
// end updateSearchIndex example
5255

5356
// start dropSearchIndex example
57+
// Dropping (deleting) a search index
5458
await collection.dropSearchIndex("search1");
5559
// end dropSearchIndex example
5660
} finally {

source/code-snippets/indexes/single-field.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
// Creating single field indexes
12
const { MongoClient } = require("mongodb");
23

3-
// Replace the following with your MongoDB deployment's connection
4-
// string.
4+
// Replace the following with your MongoDB deployment's connection string
55
const uri =
66
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
77

@@ -20,10 +20,11 @@ async function run() {
2020
// end-idx
2121

2222
// begin-query
23+
// Define the query parameters
2324
const query = { title: "Batman" }
2425
const sort = { title: 1 };
2526
const projection = { _id: 0, title: 1 };
26-
27+
// Execute the query using the defined parameters
2728
const cursor = movies
2829
.find(query)
2930
.sort(sort)

source/code-snippets/indexes/unique.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Creating a unique index
12
const { MongoClient } = require("mongodb");
23

34
// Replace the following with your MongoDB deployment's connection

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* Bulk write operation */
1+
// Bulk write operation
22

33
// Import MongoClient from the MongoDB node driver package
44
const { MongoClient } = require("mongodb");

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1+
// Watch for changes in a collection by using a change stream
12
import { MongoClient } from "mongodb";
23

34
// Replace the uri string with your MongoDB deployment's connection string.
45
const uri = "<connection string uri>";
56

67
const client = new MongoClient(uri);
78

9+
// Declare a variable to hold the change stream
810
let changeStream;
11+
12+
// Define an asynchronous function to manage the change stream
913
async function run() {
1014
try {
1115
const database = client.db("insertDB");
@@ -14,14 +18,15 @@ async function run() {
1418
// Open a Change Stream on the "haikus" collection
1519
changeStream = haikus.watch();
1620

17-
// Print change events
21+
// Print change events as they occur
1822
for await (const change of changeStream) {
1923
console.log("Received change:\n", change);
2024
}
21-
25+
// Close the change stream when done
2226
await changeStream.close();
2327

2428
} finally {
29+
// Close the MongoDB client connection
2530
await client.close();
2631
}
2732
}

0 commit comments

Comments
 (0)