Skip to content

Docsp 32718 code whisperer indexes #773

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
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
17 changes: 9 additions & 8 deletions source/code-snippets/crud/cursor.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Cursor-based document retrieval
const { MongoClient } = require("mongodb");
const stream = require("stream");

// Replace the following string with your MongoDB deployment's connection string.
// 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);

// Asynchronous iteration by using cursor methods
async function asyncIteration(myColl) {
// start async cursor example
const cursor = myColl.find({});
Expand All @@ -15,7 +16,7 @@ async function asyncIteration(myColl) {
}
// end async cursor example
}

// Manual iteration using cursor methods
async function manualIteration(myColl) {
// start manual cursor example
const cursor = myColl.find({});
Expand All @@ -25,30 +26,30 @@ async function manualIteration(myColl) {
}
// end manual cursor example
}

// Stream documents
async function streamAPI(myColl) {
// start stream cursor example
const cursor = myColl.find({});
cursor.stream().on("data", doc => console.log(doc));
// end stream cursor example
}

// Event-based iteration using cursor events
async function eventAPI(myColl) {
// start event cursor example
const cursor = myColl.find({});
// the "data" event is fired once per document
cursor.on("data", data => console.log(data));
// end event cursor example
}

// Fetch all documents as an array using the toArray method
async function fetchAll(myColl) {
// start fetchAll cursor example
const cursor = myColl.find({});
const allValues = await cursor.toArray();
// end fetchAll cursor example
console.log(allValues.length);
}

// Rewind the cursor
async function rewind(myColl) {
// start rewind cursor example
const cursor = myColl.find({});
Expand All @@ -59,7 +60,7 @@ async function rewind(myColl) {
console.log("Second count: " + secondResult.length);
// end rewind cursor example
}

// Close a cursor
async function close(myColl) {
const cursor = myColl.find({});

Expand Down
17 changes: 9 additions & 8 deletions source/code-snippets/crud/pizza.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// CRUD (Create, Read, Update, Delete) operations
const { MongoClient } = require("mongodb");

// Replace the following string with your MongoDB deployment's connection string.
Expand All @@ -13,8 +14,8 @@ async function run() {
try {
const database = client.db("test");
const orders = database.collection("orders");

// start find crud example
// Search for orders by name and within a specific date range
const findResult = await orders.find({
name: "Lemony Snicket",
date: {
Expand All @@ -24,8 +25,8 @@ async function run() {
});
// end find crud example
console.log(await findResult.toArray());

// start aggregate crud example
// Group orders by status within the last week
const aggregateResult = await orders.aggregate([
{
$match: {
Expand All @@ -46,8 +47,8 @@ async function run() {
]);
// end aggregate crud example
console.log(await aggregateResult.toArray());

// start watch crud example
// Set up a change stream to listen for new order insertions
const changeStream = orders.watch([
{ $match: { operationType: "insert" } },
{
Expand All @@ -63,10 +64,10 @@ async function run() {
});
// end watch crud example

// force change stream to instantiate so it can see the insert
// Allow the change stream to instantiate so it can see the insert
await sleep(1);

// start insert crud example
// Insert a new order document
const insertResult = await orders.insertOne({
date: new Date(Date.now()),
address: "667 Dark Avenue, San Francisco, CA, 94110",
Expand All @@ -89,8 +90,8 @@ async function run() {
});
// end insert crud example
console.log(insertResult.insertedCount); // should be 1

// start update crud example
// Update an existing order's address
const updateResult = await orders.updateOne(
{
address: "667 Dark Avenue, San Francisco, CA, 94110",
Expand All @@ -103,8 +104,8 @@ async function run() {
);
// end update crud example
console.log(updateResult.modifiedCount); // should be 1

// start delete crud example
// Delete an order document based on specified conditions
const deleteResult = await orders.deleteOne({
address: "13 Lousy Lane",
name: "Violet Baudelaire",
Expand All @@ -115,7 +116,7 @@ async function run() {
});
// end delete crud example
console.log(deleteResult.deletedCount); // should be 0

// Close the change stream and client connection
await changeStream.close();
} finally {
await client.close();
Expand Down
24 changes: 14 additions & 10 deletions source/code-snippets/crud/theaters.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// Geospatial queries using proximity to a location and a specific geographic range
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";
const client = new MongoClient(uri);

// start proximity geo example
// Find theaters within a certain proximity
async function proximity(theaters) {
// start proximity geo example
// Define the query to find theaters near a specific location
const query = {
"location.geo": {
$near: {
Expand All @@ -15,30 +17,31 @@ async function proximity(theaters) {
},
},
};

// find documents based on our query
// Find documents based on our query
const cursor = theaters.find(query);
// end proximity geo example

// print a message if no documents were found
// Print a message if no documents were found
if ((await theaters.countDocuments(query)) === 0) {
console.log("No documents found!");
}
// Iterate through the found documents and display them
for await (const doc of cursor) {
console.dir(doc);
}
}

// start range geo example
// Find theaters within a specific geographic range
async function range(theaters) {
// start range geo example
// Define the query to find theaters within a specified polygon
const query = {
"location.geo": {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[-72, 40],
[-72, 40], // Polygon coordinates defining the range
[-74, 41],
[-72, 39],
[-72, 40],
Expand All @@ -49,14 +52,15 @@ async function range(theaters) {
},
};

// find documents based on our query
// Find documents based on our query
const cursor = theaters.find(query);
// end range geo example

// print a message if no documents were found
// Print a message if no documents were found
if ((await theaters.countDocuments(query)) === 0) {
console.log("No documents found!");
}
// Iterate through the found documents and display them
for await (const doc of cursor) {
console.dir(doc);
}
Expand Down
8 changes: 6 additions & 2 deletions source/code-snippets/indexes/searchIndexes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Search Index operations
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://<user>:<password>@<cluster-url>?writeConcern=majority";

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

// start createSearchIndex example
// Create a search index
const index1 = {
name: "search1",
definition: {
Expand All @@ -29,6 +30,7 @@ async function run() {
// end createSearchIndex example

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

// start updateSearchIndex example
// Update a search index
const index2 = {
"mappings": {
"dynamic": true,
Expand All @@ -51,6 +54,7 @@ async function run() {
// end updateSearchIndex example

// start dropSearchIndex example
// Dropping (deleting) a search index
await collection.dropSearchIndex("search1");
// end dropSearchIndex example
} finally {
Expand Down
7 changes: 4 additions & 3 deletions source/code-snippets/indexes/single-field.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Creating single field indexes
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://<user>:<password>@<cluster-url>?writeConcern=majority";

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

// begin-query
// Define the query parameters
const query = { title: "Batman" }
const sort = { title: 1 };
const projection = { _id: 0, title: 1 };

// Execute the query using the defined parameters
const cursor = movies
.find(query)
.sort(sort)
Expand Down
1 change: 1 addition & 0 deletions source/code-snippets/indexes/unique.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Creating a unique index
const { MongoClient } = require("mongodb");

// Replace the following with your MongoDB deployment's connection
Expand Down
2 changes: 1 addition & 1 deletion source/code-snippets/usage-examples/bulkWrite.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* Bulk write operation */
// Bulk write operation

// Import MongoClient from the MongoDB node driver package
Copy link
Collaborator

Choose a reason for hiding this comment

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

S: remove

const { MongoClient } = require("mongodb");
Expand Down
9 changes: 7 additions & 2 deletions source/code-snippets/usage-examples/changeStream.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
// Watch for changes in a collection by using a change stream
import { MongoClient } from "mongodb";

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

const client = new MongoClient(uri);

// Declare a variable to hold the change stream
let changeStream;

// Define an asynchronous function to manage the change stream
async function run() {
try {
const database = client.db("insertDB");
Expand All @@ -14,14 +18,15 @@ async function run() {
// Open a Change Stream on the "haikus" collection
changeStream = haikus.watch();

// Print change events
// Print change events as they occur
for await (const change of changeStream) {
console.log("Received change:\n", change);
}

// Close the change stream when done
await changeStream.close();

} finally {
// Close the MongoDB client connection
await client.close();
}
}
Expand Down