### Complete replaceOne() Example with Setup Source: https://www.mongodb.com/docs/drivers/node/current/crud/update/replace A full Node.js file demonstrating `replaceOne`. It includes connection setup, query definition, the replacement document, execution, and result logging. Ensure you replace the connection string and have the 'sample_mflix' database with 'movies' collection loaded. ```javascript import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string. const uri = ""; 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 documents where the title contains "The Cat from" const query = { title: { $regex: "The Cat from" } }; // 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(); } } run().catch(console.dir); ``` -------------------------------- ### Clone and Setup Node.js MongoDB Driver Source: https://www.mongodb.com/docs/drivers/node/current/issues-and-help Clone the driver repository, navigate to the directory, install dependencies, and create a new branch for development. ```bash git clone https://github.com/mongodb/node-mongodb-native.git cd node-mongodb-native npm install git checkout -b myNewFeature ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-get-started Initializes a new Node.js project and installs Mongoose and Nodemon. Use this to set up your project environment. ```bash mkdir mongodb-mongoose cd mongodb-mongoose npm init -y npm i mongoose npm i -D nodemon ``` -------------------------------- ### Start Next.js Development Server Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel Run this command to start the local development server for your Next.js application. ```bash npm run dev ``` -------------------------------- ### Install Snappy Dependency Source: https://www.mongodb.com/docs/drivers/node/current/connect/connection-options/network-compression Install the Snappy compression algorithm dependency using npm. ```bash npm install --save snappy ``` -------------------------------- ### Install npm Dependencies Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel Install all necessary Node.js dependencies for your Next.js project. ```bash npm install ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-qe Sets up a new Node.js project, configures it to use ES modules, and installs Mongoose, the MongoDB driver, dotenv, and mongodb-client-encryption. ```bash mkdir mongoose-qe-app cd mongoose-qe-app npm init -y npm pkg set main="queryable-encryption-tutorial.js" npm pkg set type="module" npm pkg set scripts.start="node queryable-encryption-tutorial.js" npm i mongoose mongodb dotenv mongodb-client-encryption ``` -------------------------------- ### Install Zstandard Dependency Source: https://www.mongodb.com/docs/drivers/node/current/connect/connection-options/network-compression Install the Zstandard compression algorithm dependency using npm. ```bash npm install --save @mongodb-js/zstd ``` -------------------------------- ### Output of findOne Example Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/retrieve This is the expected output when running the TypeScript `findOne` example. ```javascript { title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } } ``` -------------------------------- ### updateOne() Example in TypeScript Source: https://www.mongodb.com/docs/drivers/node/current/crud/update/modify This TypeScript example demonstrates updating a single document using `updateOne()`. It includes defining an interface for the document structure and utilizes the `upsert: true` option. Proper connection setup and driver installation are required. ```typescript // Update a document import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); // Define the Movie interface interface Movie { plot: string; title: string; } async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); /* Update a document that has the title "Random Harvest" to have a plot field with the specified value */ const result = await movies.updateOne( { title: "Random Harvest" }, { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}`, }, }, /* Set the upsert option to insert a document if no documents match the filter */ { upsert: true } ); // Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)` ); } finally { // Close the connection after the operation completes await client.close(); } } // Run the program and print any thrown errors run().catch(console.dir); ``` -------------------------------- ### Install Project Dependencies Source: https://www.mongodb.com/docs/drivers/node/current/connect/multiple-connections Install Express.js for the web framework and Mongoose for MongoDB object modeling. These are the core dependencies for this tutorial. ```bash npm install express mongoose ``` -------------------------------- ### ConnectionCheckOutStartedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionCheckOutStarted event. This event indicates that an operation is attempting to acquire a connection from the pool. ```javascript ConnectionCheckOutStartedEvent { time: 2023-02-13T15:56:38.291Z, address: '...' } ``` -------------------------------- ### Example Output Source: https://www.mongodb.com/docs/drivers/node/current/crud/update/modify This shows the expected console output after successfully updating documents. ```none Updated 477 documents ``` -------------------------------- ### Install AWS SDK Credential Providers Source: https://www.mongodb.com/docs/drivers/node/current/security/authentication/aws-iam Install the necessary AWS SDK package for credential providers using npm. ```bash npm install @aws-sdk/credential-providers ``` -------------------------------- ### ServerHeartbeatStartedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring This event indicates that a server heartbeat has started. It includes the connection ID of the server being monitored. ```javascript ServerHeartbeatStartedEvent { connectionId: 'localhost:27017' } ``` -------------------------------- ### Install Dependencies and Generate Prisma Schema Source: https://www.mongodb.com/docs/drivers/node/current/integrations/prisma Install project dependencies and generate the Prisma client based on your schema configuration. Re-run `npx prisma generate` if you make further schema changes. ```shell npm install npx prisma generate ``` -------------------------------- ### ConnectionReadyEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionReady event. This event confirms that a connection has completed its handshake and is ready for operations. ```javascript ConnectionReadyEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1, durationMS: 60 } ``` -------------------------------- ### Create a Vector Search Index Source: https://www.mongodb.com/docs/drivers/node/current/reference/release-notes Specify the type of a search index when creating it. This example demonstrates creating a vector search index. This feature is available starting from driver version 6.6. ```javascript const indexName = await collection.createSearchIndex({ name: 'my-vector-search-index', type: 'vectorSearch', definition: { mappings: { dynamic: false } } }); ``` -------------------------------- ### ConnectionPoolReadyEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionPoolReady event. This event indicates that a connection pool has successfully initialized and is ready for use. ```javascript ConnectionPoolReadyEvent { time: 2023-02-13T15:56:38.440Z, address: '...' } ``` -------------------------------- ### Configure MongoDB Connection URI Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel Rename the example environment file and set your MongoDB connection string as the value for MONGODB_URI. ```none MONGODB_URI= ``` -------------------------------- ### Example Change Event Output Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/change-streams This is an example of the output you might see in your terminal when a document is inserted into the 'haikus' collection while the change stream is active. ```none Received change: { _id: { _data: '...' }, operationType: 'insert', clusterTime: new Timestamp({ t: 1675800603, i: 31 }), fullDocument: { _id: new ObjectId("..."), ... }, ns: { db: 'insertDB', coll: 'haikus' }, documentKey: { _id: new ObjectId("...") } } ``` -------------------------------- ### Sample Order with Sufficient Inventory Source: https://www.mongodb.com/docs/drivers/node/current/crud/transactions/transaction-conv An example order that can be successfully processed due to sufficient inventory. ```javascript { item: "sunblock", qty: 3 }, { item: "beach chair", qty: 1 } ``` -------------------------------- ### Build and Start Next.js Application Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel Commands to build your Next.js application for production and start the production server. This ensures getStaticProps runs at build time, not on every request. ```bash npm run build npm run start ``` -------------------------------- ### ConnectionCheckedInEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionCheckedIn event. This event is emitted when a connection is returned to the pool after an operation. ```javascript ConnectionCheckedInEvent { time: 2023-02-13T15:54:07.189Z, address: '...', connectionId: 1 } ``` -------------------------------- ### Example Query Output Source: https://www.mongodb.com/docs/drivers/node/current/get-started This is an example of the output you can expect after successfully running the Node.js application and querying for the 'Back to the Future' movie. ```json { _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ..., title: 'Back to the Future', ... } ``` -------------------------------- ### Example Application Output Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-qe This is an example of the expected output when the Mongoose application successfully inserts and queries encrypted data. ```javascript Successfully inserted the patient document. Document ID: new ObjectId('...') Found patient: { patientRecord: { billing: { type: 'Visa', number: '4111111111111111' }, ssn: '987-65-4320', billAmount: 1500 }, _id: new ObjectId('...'), patientName: 'Jon Doe', patientId: 12345678, __v: 0, __safeContent__: [ Binary.createFromBase64('EGzhQwBpf1B6W9udskSxJ8kwEEnF5P+SJPZ6ygQ9Ft8=', 0) ] } Connection closed. ``` -------------------------------- ### ConnectionCheckOutFailedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionCheckOutFailed event. This event is emitted when an operation fails to acquire a connection. ```javascript ConnectionCheckOutFailedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', reason: '...', durationMS: 60 } ``` -------------------------------- ### ServerOpeningEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring This event signals that a server is opening. It contains the topology ID and the address of the server. ```javascript ServerOpeningEvent { topologyId: 0, address: 'localhost:27017' } ``` -------------------------------- ### Start Azure Function Locally Source: https://www.mongodb.com/docs/drivers/node/current/integrations/azure-functions Run this command from your project's root directory to start your Azure Function locally. The CLI will output the local URL for your function. ```bash func start ``` -------------------------------- ### Sample Order with Insufficient Inventory Source: https://www.mongodb.com/docs/drivers/node/current/crud/transactions/transaction-conv An example order that will fail due to insufficient inventory for one of the items. ```javascript { item: "volleyball", qty: 1 } ``` -------------------------------- ### Install socks Package Source: https://www.mongodb.com/docs/drivers/node/current/security/socks Install the 'socks' package to enable SOCKS5 proxy support in your application. This is required for Node.js driver versions 6.0 and later. ```bash npm i socks ``` -------------------------------- ### Example Aggregation Output Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/retrieve This is an example of the output format you might receive after running an aggregation query that groups documents by status and counts them. ```json [ { _id: 'delivering', count: 5 }, { _id: 'delivered', count: 37 }, { _id: 'created', count: 9 } ] ``` -------------------------------- ### Example Output of find() Operation Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/retrieve This is the expected output format when running the TypeScript find() example. It shows a list of documents with the projected fields. ```javascript { title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } } { title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } } { title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } } { title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } } ... ``` -------------------------------- ### TopologyOpeningEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring This event is emitted when a topology is opening. It contains the topology ID. ```javascript TopologyOpeningEvent { topologyId: 0 } ``` -------------------------------- ### Basic Replace Operation Example Source: https://www.mongodb.com/docs/drivers/node/current/crud/update/replace Demonstrates a basic `replaceOne` operation. This example replaces a document matching the `_id` filter with a new document containing different item details. ```javascript const myDB = client.db("myDB"); const myColl = myDB.collection("items"); const filter = { _id: 501 }; // replace the matched document with the replacement document const replacementDocument = { item: "Vintage silver flatware set", price: 79.15, quantity: 1, }; const result = await myColl.replaceOne(filter, replacementDocument); ``` -------------------------------- ### Insert Sample Documents Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/distinct Inserts sample documents into the 'restaurants' collection for use in distinct value retrieval examples. ```javascript const myDB = client.db("myDB"); const myColl = myDB.collection("restaurants"); await myColl.insertMany([ { "_id": 1, "restaurant": "White Bear", "borough": "Queens", "cuisine": "Chinese" }, { "_id": 2, "restaurant": "Via Carota", "borough": "Manhattan", "cuisine": "Italian" }, { "_id": 3, "restaurant": "Borgatti's", "borough": "Bronx", "cuisine": "Italian" }, { "_id": 4, "restaurant": "Tanoreen", "borough": "Brooklyn", "cuisine": "Middle Eastern" }, { "_id": 5, "restaurant": "Äpfel", "borough": "Queens", "cuisine": "German" }, { "_id": 6, "restaurant": "Samba Kitchen", "borough": "Manhattan", "cuisine": "Brazilian" }, ]); ``` -------------------------------- ### Install MongoDB Node.js Driver Source: https://www.mongodb.com/docs/drivers/node/current/integrations/azure-functions Install the MongoDB Node.js driver from the project root using npm. This command adds the driver to your project dependencies. ```bash npm install mongodb ``` -------------------------------- ### Count Documents Example: Full File Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/count This example estimates the total number of documents in a collection and then provides an accurate count of documents matching a specific query. Ensure you have a MongoDB connection string and the 'sample_mflix' database with the 'movies' collection loaded. ```javascript import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); /* Print the estimate of the number of documents in the "movies" collection */ const estimate = await movies.estimatedDocumentCount(); console.log(`Estimated number of documents in the movies collection: ${estimate}`); /* Print the number of documents in the "movies" collection that match the specified query */ const query = { countries: "Canada" }; const countCanada = await movies.countDocuments(query); console.log(`Number of movies from Canada: ${countCanada}`); } finally { // Close the connection after the operations complete await client.close(); } } // Run the program and print any thrown exceptions run().catch(console.dir); ``` -------------------------------- ### TopologyDescriptionChangedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring This event details changes in the MongoDB deployment's topology, such as transitioning between states like 'ReplicaSetNoPrimary' and 'ReplicaSetWithPrimary'. ```javascript TopologyDescriptionChangedEvent { topologyId: 0, previousDescription: TopologyDescription { type: 'ReplicaSetNoPrimary', setName: null, maxSetVersion: null, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: null, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: null }, newDescription: TopologyDescription { type: 'ReplicaSetWithPrimary', setName: 'rs', maxSetVersion: 1, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: 30, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: 7 } } ``` -------------------------------- ### ServerDescriptionChangedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring This event is emitted when the description of a server changes. It includes details about the topology, server address, and the previous and new server descriptions. ```javascript ServerDescriptionChangedEvent { topologyId: 0, address: 'localhost:27017', previousDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089030, lastWriteDate: null, opTime: null, type: 'Unknown', minWireVersion: 0, maxWireVersion: 0, hosts: [], passives: [], arbiters: [], tags: [] }, newDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089051, lastWriteDate: 2019-10-16T18:38:07.000Z, opTime: { ts: Timestamp, t: 18 }, type: 'RSPrimary', minWireVersion: 0, maxWireVersion: 7, maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 100000, me: 'localhost:27017', hosts: [ 'localhost:27017' ], passives: [], arbiters: [], tags: [], setName: 'rs', setVersion: 1, electionId: ObjectID, primary: 'localhost:27017', logicalSessionTimeoutMinutes: 30, '$clusterTime': ClusterTime } } ``` -------------------------------- ### Initialize Node.js Project Source: https://www.mongodb.com/docs/drivers/node/current/connect/multiple-connections Create a new directory and initialize a Node.js project using npm. This sets up the basic project structure. ```bash mkdir mongodb-multiple-connections cd mongodb-multiple-connections npm init -y ``` -------------------------------- ### Execute 'hello' Command with `command()` Source: https://www.mongodb.com/docs/drivers/node/current/run-command Use the `command()` method to run the 'hello' command, which retrieves information about the current replica set member's role. This method is suitable for any database command. ```javascript const result = await myDB.command({ hello: 1 }); ``` -------------------------------- ### Get Distinct Years with Director Filter (TypeScript) Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/distinct Retrieves a list of distinct 'year' values from the 'movies' collection where the director is 'Barbra Streisand', using TypeScript. This example includes an interface for type safety. ```typescript import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string. const uri = ""; const client = new MongoClient(uri); interface Movie { directors: string; year: number; } async function run() { try { // define a database and collection on which to run the method const database = client.db("sample_mflix"); const movies = database.collection("movies"); const distinctValues = await movies.distinct("year", { directors: "Barbra Streisand", }); console.log(distinctValues); } finally { await client.close(); } } run().catch(console.dir); ``` -------------------------------- ### updateOne() Example in JavaScript Source: https://www.mongodb.com/docs/drivers/node/current/crud/update/modify Use `updateOne()` to modify the first document that matches the filter criteria. The `upsert: true` option will insert a new document if no match is found. Ensure you have the MongoDB Node.js driver installed and a connection string URI. ```javascript // Update a document import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string const uri = ""; const client = new MongoClient(uri); async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a filter for movies with the title "Random Harvest" const filter = { title: "Random Harvest" }; /* Set the upsert option to insert a document if no documents match the filter */ const options = { upsert: true }; // Specify the update to set a value for the plot field const updateDoc = { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}` }, }; // Update the first document that matches the filter const result = await movies.updateOne(filter, updateDoc, options); // Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, ); } finally { // Close the connection after the operation completes await client.close(); } } // Run the program and print any thrown errors run().catch(console.dir); ``` -------------------------------- ### Subscribe to SDAM Events Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Connect to a replica set and subscribe to specific SDAM events like 'serverOpening'. This example demonstrates how to log event details when they occur. ```javascript const client = new MongoClient(uri); const eventName = 'serverOpening'; client.on(eventName, (event) => console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`) ); try { await client.db('admin').command({ ping: 1 }); } finally { await client.close(); } ``` -------------------------------- ### Initialize Mongoose Application Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-qe Sets up the main application file with necessary imports and a placeholder for the main execution function. Ensure all required npm packages are installed. ```javascript import 'dotenv/config'; import mongoose from 'mongoose'; import * as qeHelper from './queryable-encryption-helpers.js'; import { MongoClient, ClientEncryption } from 'mongodb'; async function runExample() { // Paste initial application variables below // Paste credential and options variables below // Paste connection and client configuration below // Paste data key creation code below // Paste encryption schema below // Paste the model below // Paste connection code below // Paste the insertion operation below // Paste the encrypted query below await connection.close(); console.log('Connection closed.'); } runExample().catch(console.dir); ``` -------------------------------- ### ConnectionPoolClosedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionPoolClosed event. This event is emitted when a connection pool is closed. ```javascript ConnectionPoolClosedEvent { time: 2023-02-13T15:56:38.440Z, address: '...' } ``` -------------------------------- ### Set Up Environment Variables Source: https://www.mongodb.com/docs/drivers/node/current/connect/multiple-connections Create a .env file to store your MongoDB connection strings. Ensure you replace the placeholder values with your actual connection strings. ```javascript PRIMARY_CONN_STR= SECONDARY_CONN_STR= ``` -------------------------------- ### ConnectionCheckedOutEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionCheckedOut event. This event signifies that an operation has successfully acquired a connection. ```javascript ConnectionCheckedOutEvent { time: 2023-02-13T15:54:07.188Z, address: '...', connectionId: 1, durationMS: 60 } ``` -------------------------------- ### Create Next.js App with MongoDB Example Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel Use this command to scaffold a new Next.js application pre-configured with MongoDB integration. Replace 'sample_mflix' with your desired project name. ```bash npx create-next-app --example with-mongodb sample_mflix ``` -------------------------------- ### ConnectionPoolCreatedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionPoolCreated event. This event signifies the creation of a new connection pool. ```javascript ConnectionPoolCreatedEvent { time: 2023-02-13T15:54:06.944Z, address: '...', options: {...} } ``` -------------------------------- ### Example Documents Matching a Phrase Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/text These documents are examples of results returned when searching for the phrase 'star trek'. ```json { title: 'Star Trek' } { title: 'Star Trek Into Darkness' } { title: 'Star Trek: Nemesis' } { title: 'Star Trek: Insurrection' } { title: 'Star Trek: Generations' } { title: 'Star Trek: First Contact' } { title: 'Star Trek: The Motion Picture' } { title: 'Star Trek VI: The Undiscovered Country' } { title: 'Star Trek V: The Final Frontier' } { title: 'Star Trek IV: The Voyage Home' } { title: 'Star Trek III: The Search for Spock' } { title: 'Star Trek II: The Wrath of Khan' } ``` -------------------------------- ### Create Project Directory Source: https://www.mongodb.com/docs/drivers/node/current/get-started Use these commands to create a new directory for your Node.js project and initialize it with npm. ```bash mkdir node_quickstart ``` ```bash cd node_quickstart npm init -y ``` -------------------------------- ### ConnectionPoolClearedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionPoolCleared event. This event indicates that all connections in the pool have been closed and the pool is cleared. ```javascript ConnectionPoolClearedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', serviceId: undefined, interruptInUseConnections: true } ``` -------------------------------- ### Navigate to Project Directory Source: https://www.mongodb.com/docs/drivers/node/current/integrations/next-vercel After creating the Next.js application, change into the project directory using this command. ```bash cd sample_mflix ``` -------------------------------- ### ConnectionCreatedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionCreated event. This event is triggered when a new connection is established within the pool. ```javascript ConnectionCreatedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1 } ``` -------------------------------- ### Example Documents After Negation Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/text These documents are examples of results returned after excluding the phrase 'into darkness' from the 'star trek' search. ```json { title: 'Star Trek' } { title: 'Star Trek: Nemesis' } { title: 'Star Trek: Insurrection' } { title: 'Star Trek: Generations' } { title: 'Star Trek: First Contact' } { title: 'Star Trek: The Motion Picture' } { title: 'Star Trek VI: The Undiscovered Country' } { title: 'Star Trek V: The Final Frontier' } { title: 'Star Trek IV: The Voyage Home' } { title: 'Star Trek III: The Search for Spock' } { title: 'Star Trek II: The Wrath of Khan' } ``` -------------------------------- ### Insert Sample Documents Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/project Inserts sample fruit documents into the 'fruits' collection for use in projection examples. Ensure the MongoDB client is connected before running. ```javascript const myDB = client.db("myDB"); const myColl = myDB.collection("fruits"); await myColl.insertMany([ { "_id": 1, "name": "apples", "qty": 5, "rating": 3 }, { "_id": 2, "name": "bananas", "qty": 7, "rating": 1 }, { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }, { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }, ]); ``` -------------------------------- ### ConnectionClosedEvent Example Source: https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/monitoring Example output for a connectionClosed event. This event is emitted when a connection is closed, potentially due to pool closure or other reasons. ```javascript ConnectionClosedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', connectionId: 1, reason: 'poolClosed', serviceId: undefined } ``` -------------------------------- ### Install MongoDB Node.js Driver Source: https://www.mongodb.com/docs/drivers/node/current/get-started Install the MongoDB Node.js driver version 7.3 into your project. This command also updates your package.json file. ```bash npm install mongodb@7.3 ``` -------------------------------- ### Seed MongoDB Database with Sample Data Source: https://www.mongodb.com/docs/drivers/node/current/integrations/prisma Populate your MongoDB database with sample data by running the Prisma seed script. This command creates the collections defined in your `schema.prisma` file. ```shell npx prisma db seed ``` -------------------------------- ### Configure Database Options Source: https://www.mongodb.com/docs/drivers/node/current/crud/configure Set read preference, read concern, and write concern for a specific database by passing a DbOptions object to the db() method. This example configures primary preferred read preference, available read concern, and a majority write concern. ```javascript const dbOptions = { readPreference: ReadPreference.PRIMARY_PREFERRED, readConcern: { level: "available" }, writeConcern: { w: "majority" }, }; const db = client.db("test_database", dbOptions); ``` -------------------------------- ### Create a GridFS Bucket Instance Source: https://www.mongodb.com/docs/drivers/node/current/crud/gridfs Instantiate a GridFSBucket to interact with GridFS. Pass the database object as a parameter. The default bucket name is 'fs'. ```javascript const db = client.db(dbName); const bucket = new mongodb.GridFSBucket(db); ``` -------------------------------- ### Example Documents Sorted by Relevance Source: https://www.mongodb.com/docs/drivers/node/current/crud/query/text These documents are examples of results sorted by their text relevance score, with higher scores indicating greater relevance. ```json { title: 'Star Trek', score: 1.5 } { title: 'Star Trek: Generations', score: 1.3333333333333333 } { title: 'Star Trek: Insurrection', score: 1.3333333333333333 } { title: 'Star Trek: Nemesis', score: 1.3333333333333333 } { title: 'Star Trek: The Motion Picture', score: 1.25 } { title: 'Star Trek: First Contact', score: 1.25 } { title: 'Star Trek II: The Wrath of Khan', score: 1.2 } { title: 'Star Trek III: The Search for Spock', score: 1.2 } { title: 'Star Trek IV: The Voyage Home', score: 1.2 } { title: 'Star Trek V: The Final Frontier', score: 1.2 } { title: 'Star Trek VI: The Undiscovered Country', score: 1.2 } ``` -------------------------------- ### Configure MongoDB Connection and Client Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-qe Sets up a Mongoose connection for encrypted operations, a MongoDB client for key management, and a ClientEncryption instance. It also drops existing databases for a clean setup. ```javascript const connection = mongoose.createConnection(); const client = new MongoClient(uri); const clientEncryption = new ClientEncryption( client, autoEncryptionOptions ); await qeHelper.dropExistingDatabase(client, encryptedDatabaseName); await qeHelper.dropExistingDatabase(client, keyVaultDatabaseName); ``` -------------------------------- ### Install Validator Package Source: https://www.mongodb.com/docs/drivers/node/current/integrations/mongoose/mongoose-get-started Install the 'validator' package using npm, which is used for validating data formats like email addresses within Mongoose middleware. ```bash npm install validator ``` -------------------------------- ### Install Dotenv Package Source: https://www.mongodb.com/docs/drivers/node/current/connect/multiple-connections Install the dotenv package to load environment variables from your .env file into your Node.js application. This is crucial for managing connection strings securely. ```bash npm install dotenv ``` -------------------------------- ### Enable TLS with Connection String Source: https://www.mongodb.com/docs/drivers/node/current/security/tls Set the `tls` option to `true` in your connection string to enable TLS for the connection. ```js const uri = "mongodb://:?tls=true"; const client = new MongoClient(uri, myClientSettings); ``` -------------------------------- ### Configure MongoClient Options Source: https://www.mongodb.com/docs/drivers/node/current/crud/configure Set default read preference, read concern, and write concern for all operations by passing options to the MongoClient constructor. This example configures secondary read preference, local read concern, and a write concern of 'w: 2'. ```javascript const clientOptions = { readPreference: ReadPreference.SECONDARY, readConcern: { level: "local" }, writeConcern: { w: 2 }, }; const client = new MongoClient("mongodb://localhost:27017", clientOptions); ``` -------------------------------- ### Connect to Replica Set Source: https://www.mongodb.com/docs/drivers/node/current/connect/connection-targets Connect to a replica set by listing all nodes in the connection string for resilience. The driver can also discover remaining nodes if only one is specified. ```javascript const client = new MongoClient("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs"); ```