======================== CODE SNIPPETS ======================== TITLE: Start a Specific Stream Processor (Shell Example) DESCRIPTION: Demonstrates how to start a specific stream processor named `solarDemo` using the `start()` method in a shell environment. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/sp.processor.start.txt#_snippet_2 LANGUAGE: sh CODE: ``` sp.solarDemo.start() ``` ---------------------------------------- TITLE: Example MongoDB Daemon Start Command with Logging DESCRIPTION: Demonstrates how to start a `mongod` instance from the command line, enabling verbose logging and directing the output to a specified log file, with new data appended to the existing file. SOURCE: https://github.com/mongodb/docs/blob/master/source/administration/monitoring.txt#_snippet_8 LANGUAGE: javascript CODE: ``` mongod -v --logpath /var/log/mongodb/server1.log --logappend ``` ---------------------------------------- TITLE: Start MongoDB Instance with Configuration File DESCRIPTION: Command-line instruction to start a `mongod` instance, directing it to load its configuration from a specified YAML file. This is the standard way to apply the TLS/SSL settings defined in the configuration. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/configure-ssl.txt#_snippet_2 LANGUAGE: bash CODE: ``` mongod --config ``` ---------------------------------------- TITLE: Start MongoDB using Package Manager Init Scripts DESCRIPTION: Commands to start the MongoDB daemon on Linux and macOS systems where MongoDB was installed via a package manager, utilizing the provided initialization scripts. SOURCE: https://github.com/mongodb/docs/blob/master/source/administration/configuration.txt#_snippet_0 LANGUAGE: bash CODE: ``` sudo systemctl start mongod ``` LANGUAGE: bash CODE: ``` sudo service mongod start ``` LANGUAGE: bash CODE: ``` brew services start mongodb-community@{+version+} ``` ---------------------------------------- TITLE: Start MongoDB Daemon with Configuration File DESCRIPTION: This bash command shows how to start a `mongod` instance using a specified configuration file. The configuration file contains all the necessary settings, including TLS/SSL parameters, for the MongoDB server. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/configure-ssl.txt#_snippet_5 LANGUAGE: bash CODE: ``` mongod --config ``` ---------------------------------------- TITLE: Example: Start mongos with Kerberos and Shard Configuration DESCRIPTION: Provides a concrete example of starting `mongos` with Kerberos, specifying a keytab file, authentication mechanism, config database, key file, and bind IP addresses for a sharded cluster setup. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/control-access-to-mongodb-with-kerberos-authentication.txt#_snippet_10 LANGUAGE: bash CODE: ``` env KRB5_KTNAME=/opt/mongodb/mongos.keytab \ mongos \ --setParameter authenticationMechanisms=GSSAPI \ --configdb shard0.example.net, shard1.example.net,shard2.example.net \ --keyFile /opt/mongodb/mongos.keyfile \ --bind_ip localhost, ``` ---------------------------------------- TITLE: Example: Start MongoDB Balancer Thread DESCRIPTION: Demonstrates a simple example of how to execute the `balancerStart` command to initiate the balancer thread on a connected `mongos` instance, using its most basic form. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/balancerStart.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.adminCommand( { balancerStart: 1 } ) ``` ---------------------------------------- TITLE: Start mongosh Client in No-DB Mode DESCRIPTION: Initiates the MongoDB shell client without connecting to a database immediately. This mode is useful for executing commands that don't require an active database connection or for initial setup. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-connection-boilerplate.rst#_snippet_0 LANGUAGE: bash CODE: ``` mongosh --nodb ``` ---------------------------------------- TITLE: Example: Start mongos.exe with Kerberos and Sharded Cluster Options DESCRIPTION: An example command demonstrating how to start a mongos instance with Kerberos GSSAPI authentication, including common sharded cluster options like `--configdb`, `--keyFile` for internal authentication, and `--bind_ip` for network binding. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/control-access-to-mongodb-windows-with-kerberos-authentication.txt#_snippet_1 LANGUAGE: bash CODE: ``` mongos.exe --setParameter authenticationMechanisms=GSSAPI --configdb shard0.example.net, shard1.example.net,shard2.example.net --keyFile C:\\mongos.keyfile --bind_ip localhost, ``` ---------------------------------------- TITLE: Install MongoDB Enterprise Components and Shell with OpenSSL 1.1 DESCRIPTION: This command installs specific MongoDB Enterprise components (database and tools) along with the MongoDB Shell configured to use OpenSSL 1.1. It provides more granular control over the installation than the full enterprise package. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/install-mongodb-apt-get-commands.rst#_snippet_3 LANGUAGE: sh CODE: ``` sudo apt-get install -y mongodb-enterprise-database mongodb-enterprise-tools mongodb-mongosh-shared-openssl11 ``` ---------------------------------------- TITLE: Install MongoDB Atlas CLI via Homebrew DESCRIPTION: This command installs the MongoDB Atlas CLI, a command-line interface for managing MongoDB Atlas, using the Homebrew package manager. This is a common installation method for macOS and Linux users. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/steps-ts-quick-start-atlas-cli.rst#_snippet_0 LANGUAGE: Bash CODE: ``` brew install mongodb-atlas-cli ``` ---------------------------------------- TITLE: Create and Switch to a New MongoDB Database DESCRIPTION: Shows how to create and switch to a new database in MongoDB using the 'use' command in the mongosh shell. This command implicitly creates the database if it doesn't exist. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/steps-ts-quick-start-mongosh.rst#_snippet_1 LANGUAGE: bash CODE: ``` use timeseries ``` ---------------------------------------- TITLE: Run mongod with a Configuration File DESCRIPTION: Demonstrates the basic command to start a MongoDB daemon (`mongod`) using a specified configuration file. This command is used to apply the TLS/SSL settings defined in the configuration. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/configure-ssl.txt#_snippet_17 LANGUAGE: bash CODE: ``` mongod --config ``` ---------------------------------------- TITLE: Build MongoDB Documentation Locally DESCRIPTION: This snippet provides a sequence of commands to set up your environment and build the MongoDB documentation from its source. It covers installing the necessary Python tool 'giza', cloning the documentation repository, navigating into the project directory, and compiling the HTML documentation files. SOURCE: https://github.com/mongodb/docs/blob/master/README.rst#_snippet_0 LANGUAGE: Python CODE: ``` python2 -m pip install giza ``` LANGUAGE: Shell CODE: ``` git clone https://github.com/mongodb/docs.git ``` LANGUAGE: Shell CODE: ``` cd docs/ ``` LANGUAGE: Shell CODE: ``` make html ``` ---------------------------------------- TITLE: Install MongoDB Enterprise Components and Shell with OpenSSL 3 DESCRIPTION: This command installs specific MongoDB Enterprise components (database and tools) along with the MongoDB Shell configured to use OpenSSL 3. It provides more granular control over the installation than the full enterprise package. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/install-mongodb-apt-get-commands.rst#_snippet_4 LANGUAGE: sh CODE: ``` sudo apt-get install -y mongodb-enterprise-database mongodb-enterprise-tools mongodb-mongosh-shared-openssl3 ``` ---------------------------------------- TITLE: Start MongoDB Shard Member via Command-line Options DESCRIPTION: This example shows how to start a MongoDB `mongod` instance as a shard member using command-line options. It includes specifying the port, replica set name, and the `--shardsvr` option. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/build-indexes-on-sharded-clusters.txt#_snippet_5 LANGUAGE: bash CODE: ``` mongod --port 27018 --replSet shardA --shardsvr ``` ---------------------------------------- TITLE: Delete a Single Document with Index Hint and Setup DESCRIPTION: This comprehensive example illustrates how to use `deleteOne()` with an explicit index hint (`hint: { grade: 1 }`) to guide the query optimizer. It includes setup steps for creating a collection, inserting sample documents, and creating an index, followed by the delete operation and a method to verify index usage using `$indexStats`. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/db.collection.deleteOne.txt#_snippet_7 LANGUAGE: javascript CODE: ``` db.members.insertMany( [ { _id: 1, student: "Richard", grade: "F", points: 0 }, { _id: 2, student: "Jane", grade: "A", points: 60 }, { _id: 3, student: "Adam", grade: "F", points: 0 }, { _id: 4, student: "Ronan", grade: "D", points: 20 }, { _id: 5, student: "Noah", grade: "F", points: 0 }, { _id: 6, student: "Henry", grade: "A", points: 86 } ] ) ``` LANGUAGE: javascript CODE: ``` db.members.createIndex( { grade: 1 } ) ``` LANGUAGE: javascript CODE: ``` db.members.deleteOne( { points: { $lte: 20 }, grade: "F" }, { hint: { grade: 1 } } ) ``` LANGUAGE: javascript CODE: ``` db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] ) ``` ---------------------------------------- TITLE: Client Setup for Inserting Encrypted Documents (Queryable Encryption) DESCRIPTION: These code examples demonstrate how to initialize and configure the client for inserting encrypted documents using MongoDB's Queryable Encryption feature. The snippets cover Python, Java (sync), Go, and C# implementations, focusing specifically on the client setup portion of the code as indicated by 'start-client' and 'end-client' markers. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/queryable-encryption/tutorials/automatic/gcp/client.rst#_snippet_1 LANGUAGE: python CODE: ``` # Python client setup for Queryable Encryption # This section would contain the MongoClient initialization # and Queryable Encryption specific options for inserting documents. client = MongoClient(...) ``` LANGUAGE: java CODE: ``` // Java (sync) client setup for Queryable Encryption // This section would contain the MongoClient initialization // and Queryable Encryption specific options for inserting documents. MongoClient client = MongoClients.create(...); ``` LANGUAGE: go CODE: ``` // Go client setup for Queryable Encryption // This section would contain the mongo.Client initialization // and Queryable Encryption specific options for inserting documents. client, err := mongo.Connect(...) ``` LANGUAGE: csharp CODE: ``` // C# client setup for Queryable Encryption // This section would contain the MongoClient initialization // and Queryable Encryption specific options for inserting documents. var client = new MongoClient(...); ``` ---------------------------------------- TITLE: Install MongoDB Enterprise and Shell with OpenSSL 1.1 DESCRIPTION: This command installs the full MongoDB Enterprise package along with the MongoDB Shell configured to use OpenSSL 1.1. It assumes OpenSSL 1.1 is already present on the system. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/install-mongodb-apt-get-commands.rst#_snippet_0 LANGUAGE: sh CODE: ``` sudo apt-get install -y mongodb-enterprise mongodb-mongosh-shared-openssl11 ``` ---------------------------------------- TITLE: Remove and Install MongoDB Shell with OpenSSL 1.1 DESCRIPTION: This command first removes any existing MongoDB Shell installation and then installs the MongoDB Shell specifically configured to use OpenSSL 1.1. This is useful for switching OpenSSL versions or ensuring a clean install. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/install-mongodb-apt-get-commands.rst#_snippet_1 LANGUAGE: sh CODE: ``` sudo apt-get remove -y mongodb-mongosh && sudo apt-get install -y mongodb-mongosh-shared-openssl11 ``` ---------------------------------------- TITLE: Connect to MongoDB Deployment using mongosh DESCRIPTION: Demonstrates how to connect to a MongoDB self-managed or Atlas deployment using the mongosh shell, including specifying API version and username. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/steps-ts-quick-start-mongosh.rst#_snippet_0 LANGUAGE: bash CODE: ``` mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1 --username ``` ---------------------------------------- TITLE: Install libmongocrypt on Ubuntu-based Systems DESCRIPTION: This guide provides step-by-step instructions for installing `libmongocrypt` on Ubuntu and similar Linux distributions. The process involves importing the required GPG public key, configuring the MongoDB repository for Ubuntu, refreshing the package cache, and installing the `libmongocrypt-dev` package. SOURCE: https://github.com/mongodb/docs/blob/master/source/core/csfle/reference/libmongocrypt.txt#_snippet_2 LANGUAGE: sh CODE: ``` sudo sh -c 'curl -s --location https://pgp.mongodb.com/libmongocrypt.asc | gpg --dearmor >/etc/apt/trusted.gpg.d/libmongocrypt.gpg' ``` LANGUAGE: sh CODE: ``` echo "deb https://libmongocrypt.s3.amazonaws.com/apt/ubuntu /libmongocrypt/{+libmongocrypt-version+} universe" | sudo tee /etc/apt/sources.list.d/libmongocrypt.list ``` LANGUAGE: sh CODE: ``` sudo apt-get update ``` LANGUAGE: sh CODE: ``` sudo apt-get install -y libmongocrypt-dev ``` ---------------------------------------- TITLE: Create MongoClient with Automatic Encryption Settings DESCRIPTION: This section demonstrates how to instantiate a MongoDB client object configured with automatic encryption settings. This setup enables seamless client-side field level encryption for data operations. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/queryable-encryption/quick-start/client.rst#_snippet_2 LANGUAGE: javascript CODE: ``` // Code for MongoClient instantiation (mongosh) // From: /includes/generated/in-use-encryption/queryable-encryption/mongosh/local/reader/insert_encrypted_document.js // Section: start-client to end-client ``` LANGUAGE: javascript CODE: ``` // Code for MongoClient instantiation (Node.js) // From: /includes/generated/in-use-encryption/queryable-encryption/node/local/reader/insert_encrypted_document.js // Section: start-client to end-client ``` LANGUAGE: python CODE: ``` # Code for MongoClient instantiation (Python) # From: /includes/generated/in-use-encryption/queryable-encryption/python/local/reader/insert_encrypted_document.py # Section: start-client to end-client ``` LANGUAGE: java CODE: ``` // Code for MongoClient instantiation (Java) // From: /includes/generated/in-use-encryption/queryable-encryption/java/local/reader/src/main/java/com/mongodb/qe/InsertEncryptedDocument.java // Section: start-client to end-client ``` ---------------------------------------- TITLE: Configure and Start MongoDB Config Server Instances DESCRIPTION: This section provides configuration examples for starting MongoDB `mongod` instances as config servers, using both a YAML configuration file and direct command-line options. It covers essential settings like `sharding.clusterRole`, `replication.replSetName`, and `net.bindIp`. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/steps-deploy-sharded-cluster-config-server-noauth.rst#_snippet_0 LANGUAGE: yaml CODE: ``` sharding: clusterRole: configsvr replication: replSetName: net: bindIp: localhost, ``` LANGUAGE: bash CODE: ``` mongod --config ``` LANGUAGE: bash CODE: ``` mongod --configsvr --replSet --dbpath --bind_ip localhost, ``` ---------------------------------------- TITLE: MongoDB `transitionToDedicatedConfigServer` Command Example DESCRIPTION: A practical example demonstrating how to invoke the `transitionToDedicatedConfigServer` command to initiate the conversion of a config shard into a dedicated config server. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/transitionToDedicatedConfigServer.txt#_snippet_3 LANGUAGE: javascript CODE: ``` db.adminCommand( { transitionToDedicatedConfigServer: 1 } ) ``` ---------------------------------------- TITLE: Start Balancer using adminCommand DESCRIPTION: This example demonstrates how to start the MongoDB sharding balancer by executing the `balancerStart` command against the `admin` database. This approach is typically used when interacting with MongoDB from a driver. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/manage-sharded-cluster-balancer.txt#_snippet_9 LANGUAGE: javascript CODE: ``` db.adminCommand( { balancerStart: 1 } ) ``` ---------------------------------------- TITLE: Download Golang Dependencies for Queryable Encryption Tutorial DESCRIPTION: Execute the `go get` command to download all necessary dependencies for the `go-qe-tutorial` project. This command resolves and fetches modules as defined in the `go.mod` file. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/go/README.md#_snippet_1 LANGUAGE: golang CODE: ``` go get go-qe-tutorial ``` ---------------------------------------- TITLE: Example Document Structure for CSFLE Quick Start DESCRIPTION: Provides an example of the document structure inserted into the `patients` collection within the `medicalRecords` database, as used in the CSFLE Quick Start guide. It includes fields like `ssn`, `bloodType`, `medicalRecords`, and `insurance.policyNumber`. SOURCE: https://github.com/mongodb/docs/blob/master/source/core/csfle/fundamentals/create-schema.txt#_snippet_3 LANGUAGE: json CODE: ``` { "ssn": "", "bloodType": "", "medicalRecords": [ { "date": "", "diagnosis": "" } ], "insurance": { "provider": "", "policyNumber": "" } } ``` ---------------------------------------- TITLE: Example: Create pizzaOrders Collection and Index (JavaScript) DESCRIPTION: Initializes the example environment by creating the `pizzaOrders` collection with sample documents and an ascending index on the `orderDate` field. This setup is used for demonstrating query settings management. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/removeQuerySettings.txt#_snippet_4 LANGUAGE: javascript CODE: ``` // Create pizzaOrders collection db.pizzaOrders.insertMany( [ { _id: 0, type: "pepperoni", totalNumber: 5, orderDate: new Date( "2024-01-15T12:00:00Z" ) }, { _id: 1, type: "cheese", totalNumber: 15, orderDate: new Date( "2024-01-23T11:12:32Z" ) }, { _id: 2, type: "vegan", totalNumber: 20, orderDate: new Date( "2024-03-20T10:01:12Z" ) } ] ) // Create ascending index on orderDate field db.pizzaOrders.createIndex( { orderDate: 1 } ) ``` ---------------------------------------- TITLE: Install libmongocrypt on Debian-based Systems DESCRIPTION: This comprehensive guide outlines the steps to install `libmongocrypt` on Debian and compatible Linux distributions. It covers importing the necessary GPG public key, adding the MongoDB repository to package sources, updating the local package cache, and finally installing the `libmongocrypt-dev` package. SOURCE: https://github.com/mongodb/docs/blob/master/source/core/csfle/reference/libmongocrypt.txt#_snippet_1 LANGUAGE: sh CODE: ``` sudo sh -c 'curl -s --location https://pgp.mongodb.com/libmongocrypt.asc | gpg --dearmor >/etc/apt/trusted.gpg.d/libmongocrypt.gpg' ``` LANGUAGE: sh CODE: ``` echo "deb https://libmongocrypt.s3.amazonaws.com/apt/debian /libmongocrypt/{+libmongocrypt-version+} main" | sudo tee /etc/apt/sources.list.d/libmongocrypt.list ``` LANGUAGE: sh CODE: ``` sudo apt-get update ``` LANGUAGE: sh CODE: ``` sudo apt-get install -y libmongocrypt-dev ``` ---------------------------------------- TITLE: Initialize 'students' Collection for Examples DESCRIPTION: Inserts an initial document into the 'students' collection, providing a starting dataset for demonstrating subsequent $push operator examples. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/update/push.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.students.insertOne( { _id: 1, scores: [ 44, 78, 38, 80 ] } ) ``` ---------------------------------------- TITLE: MongoDB Example Data Setup DESCRIPTION: Inserts sample documents into `restaurant` and `students` collections for demonstration purposes of `updateOne()` operations. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/db.collection.updateOne.txt#_snippet_8 LANGUAGE: javascript CODE: ``` db.restaurant.insertMany( [ { _id: 1, name: "Central Perk Cafe", Borough: "Manhattan" }, { _id: 2, name: "Rock A Feller Bar and Grill", Borough: "Queens", violations: 2 }, { _id: 3, name: "Empire State Pub", Borough: "Brooklyn", violations: 0 } ] ) ``` LANGUAGE: javascript CODE: ``` db.students.insertMany( [ { _id: 1, student: "Skye", points: 75, commentsSemester1: "great at math", commentsSemester2: "loses temper", lastUpdate: ISODate("2019-01-01T00:00:00Z") }, { _id: 2, student: "Elizabeth", points: 60, commentsSemester1: "well behaved", commentsSemester2: "needs improvement", lastUpdate: ISODate("2019-01-01T00:00:00Z") } ] ) ``` ---------------------------------------- TITLE: Systemd Install Section for MongoDB Service DESCRIPTION: Defines the installation target for the MongoDB service unit file, ensuring it's started with multi-user services. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/control-access-to-mongodb-with-kerberos-authentication.txt#_snippet_5 LANGUAGE: ini CODE: ``` [Install] WantedBy=multi-user.target ``` ---------------------------------------- TITLE: Build and Run Java Project with Maven DESCRIPTION: Commands to clean, package, and run the Java Queryable Encryption tutorial application using Maven from the command line. This sequence ensures a fresh build before execution. If using KMIP for key management, additional JVM options might be required. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/java/README.md#_snippet_1 LANGUAGE: sh CODE: ``` mvn clean package java -jar target/queryable-encryption-tutorial.jar ``` ---------------------------------------- TITLE: Define Encrypted Schema for MongoDB Collection DESCRIPTION: This snippet shows how to create an encrypted schema for a MongoDB collection, a critical step for enabling Queryable Encryption. Examples are provided for different language drivers. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/queryable-encryption/tutorials/automatic/aws/client.rst#_snippet_2 LANGUAGE: javascript CODE: ``` // Code for creating an encrypted schema. // Extracted from: /includes/generated/in-use-encryption/queryable-encryption/mongosh/aws/reader/insert_encrypted_document.js // Section: 'start-schema' to 'end-schema' ``` LANGUAGE: javascript CODE: ``` // Code for creating an encrypted schema. // Extracted from: /includes/generated/in-use-encryption/queryable-encryption/node/aws/reader/insert_encrypted_document.js // Section: 'start-schema' to 'end-schema' ``` ---------------------------------------- TITLE: Run Compiled Golang Queryable Encryption Application DESCRIPTION: Execute the compiled Queryable Encryption application. Upon successful execution, the application will process and print a sample document to the console, demonstrating the encryption capabilities. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/go/README.md#_snippet_3 LANGUAGE: sh CODE: ``` ./go-qe-tutorial ``` ---------------------------------------- TITLE: Remove and Install MongoDB Shell with OpenSSL 3 DESCRIPTION: This command first removes any existing MongoDB Shell installation and then installs the MongoDB Shell specifically configured to use OpenSSL 3. This is useful for switching OpenSSL versions or ensuring a clean install. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/install-mongodb-apt-get-commands.rst#_snippet_2 LANGUAGE: sh CODE: ``` sudo apt-get remove -y mongodb-mongosh && sudo apt-get install -y mongodb-mongosh-shared-openssl3 ``` ---------------------------------------- TITLE: Create MongoDB Enterprise APT Repository List File for Ubuntu 22.04 DESCRIPTION: This command creates the APT source list file for MongoDB Enterprise on Ubuntu 22.04 (Jammy). It adds the official MongoDB repository to your system's package sources, allowing you to install MongoDB server packages. Remember to replace `{+version+}` with the specific MongoDB version you intend to install. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/deploy/code/enterprise-ubuntu22-conf.rst#_snippet_0 LANGUAGE: bash CODE: ``` echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-{+version+}.gpg ] https://repo.mongodb.com/apt/ubuntu jammy/mongodb-enterprise/{+version+} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-enterprise-{+version+}.list ``` ---------------------------------------- TITLE: MongoDB Example: Remove Fields Starting with Dollar Signs with $unsetField DESCRIPTION: This example demonstrates how to remove a field that starts with a dollar sign, such as '$price', from documents in a MongoDB collection. It inserts sample data and then uses an aggregation pipeline with $replaceWith, $unsetField, and the $literal operator to correctly reference and remove the field. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/unsetField.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.inventory.insertMany( [ { _id: 1, item: "sweatshirt", qty: 300, "$price": 45.99 }, { _id: 2, item: "winter coat", qty: 200, "$price": 499.99 }, { _id: 3, item: "sun dress", qty: 250, "$price": 199.99 }, { _id: 4, item: "leather boots", qty: 300, "$price": 249.99 }, { _id: 5, item: "bow tie", qty: 180, "$price": 9.99 } ] ) ``` LANGUAGE: javascript CODE: ``` db.inventory.aggregate( [ { $replaceWith: { $unsetField: { field: { $literal: "$price" }, input: "$$ROOT" } } } ] ) ``` LANGUAGE: json CODE: ``` [ { _id: 1, item: 'sweatshirt', qty: 300 }, { _id: 2, item: 'winter coat', qty: 200 }, { _id: 3, item: 'sun dress', qty: 250 }, { _id: 4, item: 'leather boots', qty: 300 }, { _id: 5, item: 'bow tie', qty: 180 } ] ``` ---------------------------------------- TITLE: Start MongoDB with Custom Configuration File DESCRIPTION: Commands to start the MongoDB daemon using a specified configuration file on Linux, demonstrating both the long-form `--config` and shorthand `-f` options. SOURCE: https://github.com/mongodb/docs/blob/master/source/administration/configuration.txt#_snippet_1 LANGUAGE: bash CODE: ``` mongod --config /etc/mongod.conf mongod -f /etc/mongod.conf ``` ---------------------------------------- TITLE: Setup MongoDB Users Collection DESCRIPTION: Inserts multiple user documents into the `users` collection to prepare data for subsequent query examples demonstrating `find()` options. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/db.collection.find.txt#_snippet_44 LANGUAGE: javascript CODE: ``` db.users.insertMany( [ { username: "david", age: 27 }, { username: "amanda", age: 25 }, { username: "rajiv", age: 32 }, { username: "rajiv", age: 90 } ] ) ``` ---------------------------------------- TITLE: Start MongoDB with systemctl DESCRIPTION: Demonstrates the recommended method to start the MongoDB daemon using systemctl. This approach ensures that system-wide ulimit settings are properly applied to the mongod process. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/ulimit.txt#_snippet_2 LANGUAGE: bash CODE: ``` systemctl start mongod.service ``` ---------------------------------------- TITLE: MongoDB transitionFromDedicatedConfigServer Command Example DESCRIPTION: Provides a practical example of how to execute the `transitionFromDedicatedConfigServer` command to reconfigure a dedicated config server to function as a config shard within a MongoDB sharded cluster. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/transitionFromDedicatedConfigServer.txt#_snippet_3 LANGUAGE: javascript CODE: ``` db.adminCommand( { transitionFromDedicatedConfigServer: 1 } ) ``` ---------------------------------------- TITLE: Example Bash Command for TLS/SSL Connections DESCRIPTION: This snippet shows a basic bash command related to a `mongod` instance configured for TLS/SSL connections. The context implies it's for connecting to or interacting with such an instance. SOURCE: https://github.com/mongodb/docs/blob/master/source/tutorial/configure-ssl.txt#_snippet_16 LANGUAGE: bash CODE: ``` ``` ---------------------------------------- TITLE: Example: Get Stream Processor Statistics with sp.solarDemo.stats() DESCRIPTION: Demonstrates how to invoke `sp.processor.stats()` for a specific stream processor named `solarDemo` and provides an example of the detailed JSON response, including processor status, message counts, sizes, state size, watermark, and pipeline definition. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/sp.processor.stats.txt#_snippet_2 LANGUAGE: sh CODE: ``` sp.solarDemo.stats() ``` LANGUAGE: json CODE: ``` { ok: 1, ns: '6500aa277fdbdb6e443a992e.63c1928d768e39423386aa16.solarDemo', stats: { name: 'solarDemo', processorId: '65f9fea5c5154385174af71e', status: 'running', scaleFactor: Long('1'), inputMessageCount: Long('926'), inputMessageSize: 410310, outputMessageCount: Long('383'), outputMessageSize: 425513, dlqMessageCount: Long('0'), dlqMessageSize: Long('0'), stateSize: Long('4504'), watermark: ISODate('2024-03-19T22:16:49.523Z'), ok: 1 }, pipeline: [ { '$source': { connectionName: 'sample_stream_solar', timeField: { '$dateFromString': { dateString: '$timestamp' } } } }, { '$match': { '$expr': { '$ne': [ '$device_id', 'device_8' ] } } }, { '$tumblingWindow': { interval: { size: 10, unit: 'second' }, pipeline: [ { '$group': { _id: [Object], max_temp: [Object], max_watts: [Object], min_watts: [Object], avg_watts: [Object], median_watts: [Object] } } ] } }, { '$merge': { into: { connectionName: 'mongodb1', db: 'solar_db', coll: 'solar_coll' }, on: [ '_id' ] } } ] } ``` ---------------------------------------- TITLE: Build and Run Java Project with Gradle DESCRIPTION: Command to clean, build, and run the Java Queryable Encryption tutorial application using Gradle from the command line. This single command streamlines the development workflow for Gradle-based projects. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/java/README.md#_snippet_2 LANGUAGE: sh CODE: ``` gradle clean build run ``` ---------------------------------------- TITLE: Execute mongosh Application Script DESCRIPTION: This command runs a specified JavaScript application script (`queryable-encryption-tutorial.js`) using the `mongosh` shell. The `-f` flag tells `mongosh` to execute the provided file, which contains the logic for the Queryable Encryption tutorial. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/mongosh/README.md#_snippet_2 LANGUAGE: shell CODE: ``` mongosh -f queryable-encryption-tutorial.js ``` ---------------------------------------- TITLE: Create MongoDB APT List File for Ubuntu 24.04 (Noble) DESCRIPTION: This bash command creates the APT source list file for MongoDB Enterprise on Ubuntu 24.04 (Noble). It echoes the repository line, including architecture and GPG key details, and pipes it to `sudo tee` to write it to the appropriate location in `/etc/apt/sources.list.d/`. This step is crucial for APT to locate and install MongoDB packages. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/deploy/code/enterprise-ubuntu24-conf.rst#_snippet_0 LANGUAGE: bash CODE: ``` echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-{+version+}.gpg ] https://repo.mongodb.com/apt/ubuntu noble/mongodb-enterprise/{+version+} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-enterprise-{+version+}.list ``` ---------------------------------------- TITLE: Initialize MongoDB Replica Set with mtools DESCRIPTION: Use the `mlaunch` command from `mtools` to initialize a MongoDB replica set with three nodes. This setup is a prerequisite for running the Queryable Encryption tutorial. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/go/README.md#_snippet_0 LANGUAGE: sh CODE: ``` mlaunch init --replicaset --nodes 3 ``` ---------------------------------------- TITLE: Start MongoDB Daemon with Configuration File DESCRIPTION: This command starts the `mongod` daemon, instructing it to load its configuration from the specified `/etc/mongod.conf` file. This method is recommended for production deployments to manage settings like data paths, replica set details, and network bindings. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/tip-repl-set-config.rst#_snippet_0 LANGUAGE: bash CODE: ``` mongod --config /etc/mongod.conf ``` ---------------------------------------- TITLE: Connect to MongoDB Shell with Authentication DESCRIPTION: Shows how to establish a connection to a local MongoDB instance using the `mongosh` command-line shell, including specifying an API version and a username for authentication. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/connection-examples-by-language-local.rst#_snippet_0 LANGUAGE: shell CODE: ``` mongosh "mongodb://localhost" --apiVersion 1 --username myDatabaseUser ``` ---------------------------------------- TITLE: Syntax for sp.processor.start() Method DESCRIPTION: Illustrates the basic syntax for invoking the `sp.processor.start()` method, showing it takes no arguments. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/sp.processor.start.txt#_snippet_1 LANGUAGE: json CODE: ``` sp.processor.start() ``` ---------------------------------------- TITLE: Create MongoDB APT Source List for Ubuntu 22.04 DESCRIPTION: This command creates the APT source list file for MongoDB on Ubuntu 22.04 (Jammy). It adds the official MongoDB repository to your system's package sources, allowing you to install MongoDB packages using `apt`. The command uses `sudo tee` to write the repository line to `/etc/apt/sources.list.d/mongodb-org-{+version+}.list`, where `{+version+}` is a placeholder for the MongoDB version. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/deploy/code/community-ubuntu22-conf.rst#_snippet_0 LANGUAGE: bash CODE: ``` echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-{+version+}.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/{+version+} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-{+version+}.list ``` ---------------------------------------- TITLE: Create MongoDB Enterprise APT List File for Ubuntu 20.04 DESCRIPTION: This bash command creates or updates the APT source list file for MongoDB Enterprise on Ubuntu 20.04 (Focal Fossa). It uses `echo` to print the repository line and `sudo tee` to write it to `/etc/apt/sources.list.d/mongodb-enterprise-{+version+}.list` with root privileges, enabling the system to find and install MongoDB packages. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/deploy/code/enterprise-ubuntu20-conf.rst#_snippet_0 LANGUAGE: bash CODE: ``` echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-{+version+}.gpg ] http://repo.mongodb.com/apt/ubuntu focal/mongodb-enterprise/{+version+} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-enterprise-{+version+}.list ``` ---------------------------------------- TITLE: Start MongoDB Shard Server via Command Line DESCRIPTION: This command initializes a `mongod` instance as a shard server. It specifies essential parameters like the replica set name, network port, data directory, and allowed bind IP addresses. This method is used for starting the server during initial setup or after maintenance. SOURCE: https://github.com/mongodb/docs/blob/master/source/release-notes/6.0-upgrade-sharded-cluster.txt#_snippet_10 LANGUAGE: bash CODE: ``` mongod --shardsvr --replSet --port --dbpath --bind_ip localhost, ``` ---------------------------------------- TITLE: Connect to MongoDB Instance (JavaScript) DESCRIPTION: Example demonstrating how to establish a connection to a MongoDB instance running on localhost and obtain a reference to a specific database using the `connect()` method. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/connect.txt#_snippet_1 LANGUAGE: javascript CODE: ``` db = connect("localhost:27017/myDatabase") ``` ---------------------------------------- TITLE: MongoDB $regexMatch: Case-Insensitive and Multiline Aggregation Example DESCRIPTION: An example MongoDB aggregation pipeline combining the 'i' (case-insensitive) and 'm' (multiline) options with $regexMatch to find lines starting with 's' or 'S' in multiline strings. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/regexMatch.txt#_snippet_9 LANGUAGE: javascript CODE: ``` db.products.aggregate([ { $addFields: { result: { $regexMatch: { input: "$description", regex: /^s/im } } } } ]) ``` ---------------------------------------- TITLE: Start MongoDB with Configuration File using --config DESCRIPTION: Demonstrates how to start a MongoDB `mongod` or `mongos` instance by specifying the configuration file path using the `--config` command-line option. This is the verbose way to provide the configuration file. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/configuration-options.txt#_snippet_1 LANGUAGE: bash CODE: ``` mongod --config /etc/mongod.conf mongos --config /etc/mongos.conf ``` ---------------------------------------- TITLE: Create Example Collection and Indexes for Query Settings DESCRIPTION: Initializes the `pizzaOrders` collection with sample documents and creates two ascending indexes on `orderDate` and `totalNumber` fields. This setup is used for demonstrating query settings. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/querySettings.txt#_snippet_2 LANGUAGE: javascript CODE: ``` // Create pizzaOrders collection db.pizzaOrders.insertMany( [ { _id: 0, type: "pepperoni", totalNumber: 5, orderDate: new Date( "2024-01-15T12:00:00Z" ) }, { _id: 1, type: "cheese", totalNumber: 15, orderDate: new Date( "2024-01-23T11:12:32Z" ) }, { _id: 2, type: "vegan", totalNumber: 20, orderDate: new Date( "2024-03-20T10:01:12Z" ) } ] ) // Create ascending index on orderDate field db.pizzaOrders.createIndex( { orderDate: 1 } ) // Create ascending index on totalNumber field db.pizzaOrders.createIndex( { totalNumber: 1 } ) ``` ---------------------------------------- TITLE: MongoDB JavaScript Example: Start Multiple Index Builds DESCRIPTION: Illustrates how to use `db.collection.createIndexes()` to initiate the creation of multiple indexes on a collection. This operation starts the index build process, which can then be managed by commands like `setIndexCommitQuorum`. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/setIndexCommitQuorum.txt#_snippet_1 LANGUAGE: javascript CODE: ``` db.getSiblingDB("examples").invoices.createIndexes( [ { "invoices" : 1 }, { "fulfillmentStatus" : 1 } ] ) ``` ---------------------------------------- TITLE: Create MongoDB Replica Set with mlaunch DESCRIPTION: This command initializes a three-node replica set using the `mlaunch` utility from `mtools`. It's useful for setting up a local MongoDB environment for development and testing purposes, specifically for scenarios requiring a replica set. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/mongosh/README.md#_snippet_0 LANGUAGE: shell CODE: ``` mlaunch init --replicaset --nodes 3 ``` ---------------------------------------- TITLE: Execute MongoDB Compass Installation Script DESCRIPTION: Commands to run the platform-specific MongoDB Compass installation script (`install_compass` or `Install-Compass.ps1`) after navigating to the `bin` directory. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/program/install_compass.txt#_snippet_1 LANGUAGE: bash CODE: ``` ./install_compass ``` LANGUAGE: powershell CODE: ``` powershell .\Install-Compass.ps1 ``` ---------------------------------------- TITLE: db.serverCmdLineOpts() DESCRIPTION: Returns a document with information about the runtime used to start the MongoDB instance. Wraps `getCmdLineOpts`. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/js-database.txt#_snippet_31 LANGUAGE: APIDOC CODE: ``` db.serverCmdLineOpts() Description: Returns a document with information about the runtime used to start the MongoDB instance. Wraps: getCmdLineOpts ``` ---------------------------------------- TITLE: Re-create MongoDB 'students2' Collection for Aggregation Example DESCRIPTION: Inserts initial documents into the 'students2' collection, serving as the starting data for demonstrating updates using an aggregation pipeline. This is a fresh dataset for the subsequent example. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/findAndModify.txt#_snippet_24 LANGUAGE: javascript CODE: ``` db.students2.insertMany( [ { "_id" : 1, "grades" : [ { "grade" : 80, "mean" : 75, "std" : 6 }, { "grade" : 85, "mean" : 90, "std" : 4 }, { "grade" : 85, "mean" : 85, "std" : 6 } ] }, { "_id" : 2, "grades" : [ { "grade" : 90, "mean" : 75, "std" : 6 }, { "grade" : 87, "mean" : 90, "std" : 3 }, { "grade" : 85, "mean" : 85, "std" : 4 } ] } ] ) ``` ---------------------------------------- TITLE: Setup: Insert Articles and Create Text Index DESCRIPTION: Inserts sample documents into the 'articles' collection and creates a text index on the 'title' field. This setup is required for demonstrating the '$meta: "textScore"' examples. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/meta.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.articles.insertMany([ { "_id" : 1, "title" : "cakes and ale" }, { "_id" : 2, "title" : "more cakes" }, { "_id" : 3, "title" : "bread" }, { "_id" : 4, "title" : "some cakes" }, { "_id" : 5, "title" : "two cakes to go" }, { "_id" : 6, "title" : "pie" } ]) ``` LANGUAGE: javascript CODE: ``` db.articles.createIndex( { title: "text"} ) ``` ---------------------------------------- TITLE: Example: Sampling from a Stream Processor with sp.solarDemo.sample() DESCRIPTION: A practical example demonstrating how to use sp.solarDemo.sample() to retrieve sampled data from a stream processor, followed by the typical JSON output structure including device metrics and stream window metadata. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/sp.processor.sample.txt#_snippet_2 LANGUAGE: sh CODE: ``` sp.solarDemo.sample() ``` LANGUAGE: json CODE: ``` { _id: { device_id: 'device_5' }, max_temp: 8, max_watts: 66, min_watts: 66, avg_watts: 66, median_watts: 66, _stream_meta: { window: { start: ISODate('2024-03-19T22:09:10.000Z'), end: ISODate('2024-03-19T22:09:20.000Z') } } } { _id: { device_id: 'device_0' }, max_temp: 18, max_watts: 210, min_watts: 68, avg_watts: 157, median_watts: 193, _stream_meta: { window: { start: ISODate('2024-03-19T22:09:10.000Z'), end: ISODate('2024-03-19T22:09:20.000Z') } } } { _id: { device_id: 'device_10' }, max_temp: 21, max_watts: 128, min_watts: 4, avg_watts: 66, median_watts: 4, _stream_meta: { window: { start: ISODate('2024-03-19T22:09:10.000Z'), end: ISODate('2024-03-19T22:09:20.000Z') } } } { _id: { device_id: 'device_9' }, max_temp: 10, max_watts: 227, min_watts: 66, avg_watts: 131.4, median_watts: 108, _stream_meta: { window: { start: ISODate('2024-03-19T22:09:10.000Z'), end: ISODate('2024-03-19T22:09:20.000Z') } } } ``` ---------------------------------------- TITLE: Create MongoDB APT Repository List File for Ubuntu 24.04 DESCRIPTION: This command creates the APT source list file for MongoDB on Ubuntu 24.04 (Noble). It adds the official MongoDB repository to the system's package sources, ensuring that the correct MongoDB packages can be installed and updated. The command uses `tee` with `sudo` to write the repository definition to `/etc/apt/sources.list.d/mongodb-org-{+version+}.list`. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/deploy/code/community-ubuntu24-conf.rst#_snippet_0 LANGUAGE: bash CODE: ``` echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-{+version+}.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/{+version+} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-{+version+}.list ``` ---------------------------------------- TITLE: Connect to MongoDB using mongosh Shell DESCRIPTION: Demonstrates how to connect to a MongoDB instance from the `mongosh` command-line shell, specifying a database, API version, and username. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/connection-examples-by-language-records-local.rst#_snippet_0 LANGUAGE: bash CODE: ``` mongosh "mongodb://localhost/records" --apiVersion 1 --username myDatabaseUser ``` ---------------------------------------- TITLE: Example Documents in config.settings Collection DESCRIPTION: JavaScript examples illustrating common configuration documents found in the `config.settings` collection, specifically for `chunksize` and `balancer` settings. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/config-database.txt#_snippet_14 LANGUAGE: javascript CODE: ``` { "_id" : "chunksize", "value" : 64 } ``` LANGUAGE: javascript CODE: ``` { "_id" : "balancer", "mode" : "full", "stopped" : false } ``` ---------------------------------------- TITLE: MongoDB rs.initiate() Method API Documentation DESCRIPTION: Detailed API documentation for the `rs.initiate()` method, including its optional replica set configuration document and key fields like `_id` and `members` array. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/initiate-replica-set.rst#_snippet_0 LANGUAGE: APIDOC CODE: ``` Method: rs.initiate() Description: Initiates a replica set. Usage: From mongosh, run the rs.initiate() method. Optional Parameter: replica set configuration document Description: A document specifying the replica set's configuration. Fields within the configuration document: - _id: Type: string Description: The replica set name, matching either the replication.replSetName setting or the --replSet option. - members: Type: array Description: An array of documents, with each document representing a member of the replica set. ``` ---------------------------------------- TITLE: Example: Using explain in queryPlanner Mode DESCRIPTION: Demonstrates how to use the `explain` command with the `queryPlanner` verbosity mode to get query planning information for a `count` operation on the 'products' collection, filtering by quantity greater than 50. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/explain.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.runCommand( { explain: { count: "products", query: { quantity: { $gt: 50 } } }, verbosity: "queryPlanner" } ) ``` ---------------------------------------- TITLE: MongoDB Session Workflow Log Message Example DESCRIPTION: An example of a MongoDB session workflow log message (starting in 6.3) that indicates slow network response send times, detailing various elapsed time metrics for an operation. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/log-messages.txt#_snippet_61 LANGUAGE: json CODE: ``` { "t": { "$date": "2022-12-14T17:22:44.233+00:00" }, "s": "I", "c": "EXECUTOR", "id": 6983000, "ctx": "conn1", "svc": "R", "msg": "Slow network response send time", "attr": { "elapsed": { "totalMillis": 109, "activeMillis": 30, "receiveWorkMillis": 2, "processWorkMillis": 10, "sendResponseMillis": 22, "yieldMillis": 15, "finalizeMillis": 30 } } } ``` ---------------------------------------- TITLE: Specify Shared Library Location for Mongosh DESCRIPTION: This snippet illustrates that the mongosh shell environment does not require users to explicitly specify the location of the Queryable Encryption shared library. Mongosh handles this configuration automatically, simplifying the setup process for shell users. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/queryable-encryption/tutorials/automatic/azure/client.rst#_snippet_0 LANGUAGE: none CODE: ``` // mongosh does not require you to specify the // location of the {+shared-library+} ``` ---------------------------------------- TITLE: Initialize MongoDB Replica Set with Custom Configuration DESCRIPTION: This JavaScript example demonstrates how to use `rs.initiate()` to set up a new replica set named 'myReplSet' with three specified members. It assumes the `mongod` instances are already running with the correct `--replSet` and `--bind_ip` options, and `mongosh` is connected to one of them. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/rs.initiate.txt#_snippet_1 LANGUAGE: javascript CODE: ``` rs.initiate( { _id: "myReplSet", version: 1, members: [ { _id: 0, host : "mongodb0.example.net:27017" }, { _id: 1, host : "mongodb1.example.net:27017" }, { _id: 2, host : "mongodb2.example.net:27017" } ] } ) ``` ---------------------------------------- TITLE: Setup: Insert Orders and Create Compound Index DESCRIPTION: Inserts sample documents into the 'orders' collection and creates a compound index on the 'type' and 'item' fields. This setup is necessary for demonstrating the '$meta: "indexKey"' examples. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/meta.txt#_snippet_5 LANGUAGE: javascript CODE: ``` db.orders.insertMany([ { "item" : "abc", "price" : NumberDecimal("12"), "quantity" : 2, "type": "apparel" }, { "item" : "jkl", "price" : NumberDecimal("20"), "quantity" : 1, "type": "electronics" }, { "item" : "abc", "price" : NumberDecimal("10"), "quantity" : 5, "type": "apparel" } ]) ``` LANGUAGE: javascript CODE: ``` db.orders.createIndex( { type: 1, item: 1 } ) ``` ---------------------------------------- TITLE: MongoDB insertMany for students Collection Example DESCRIPTION: Provides sample `insertMany` commands to populate a `students` collection with documents containing `_id` and `grades` arrays. This setup is used as a prerequisite for subsequent update examples. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/update/positional-filtered.txt#_snippet_6 LANGUAGE: javascript CODE: ``` db.students.insertMany( [ { "_id" : 1, "grades" : [ 95, 92, 90 ] }, { "_id" : 2, "grades" : [ 98, 100, 102 ] }, { "_id" : 3, "grades" : [ 95, 110, 100 ] } ] ) ``` ---------------------------------------- TITLE: Retrieve All Startup Parameters (JavaScript) DESCRIPTION: This example demonstrates how to use `db.adminCommand` with the `getParameters` command to fetch all parameters that were set at server startup, by specifying `allParameters: true` and `setAt: 'startup'`. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/getParameter.txt#_snippet_5 LANGUAGE: javascript CODE: ``` db.adminCommand( { getParameters: { allParameters: true, setAt: "startup" } } ) ``` ---------------------------------------- TITLE: MongoDB Example: Setting up Data for $mergeObjects Accumulator DESCRIPTION: This snippet provides the initial data setup for an example demonstrating $mergeObjects used as an accumulator. It inserts sample sales documents into a sales collection, which can then be used in a subsequent aggregation pipeline. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/operator/aggregation/mergeObjects.txt#_snippet_3 LANGUAGE: JavaScript CODE: ``` db.sales.insertMany( [ { _id: 1, year: 2017, item: "A", quantity: { "2017Q1": 500, "2017Q2": 500 } }, { _id: 2, year: 2016, item: "A", quantity: { "2016Q1": 400, "2016Q2": 300, "2016Q3": 0, "2016Q4": 0 } } , { _id: 3, year: 2017, item: "B", quantity: { "2017Q1": 300 } } ] ) ``` ---------------------------------------- TITLE: Start MongoDB with custom configuration DESCRIPTION: Illustrates how to start the MongoDB daemon directly with a configuration file. It's important to note that this method might lead to systemd overriding ulimit settings with user slice limits, potentially impacting resource allocation. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/ulimit.txt#_snippet_3 LANGUAGE: bash CODE: ``` mongod --config ~/mongod.conf ``` ---------------------------------------- TITLE: Set waitForSecondaryBeforeNoopWriteMS at Startup and Runtime DESCRIPTION: Examples demonstrating how to configure the `waitForSecondaryBeforeNoopWriteMS` parameter to 20 milliseconds, both when starting the `mongod` process and dynamically at runtime using the `setParameter` command in the MongoDB shell. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/parameters.txt#_snippet_145 LANGUAGE: bash CODE: ``` mongod --setParameter waitForSecondaryBeforeNoopWriteMS=20 ``` LANGUAGE: javascript CODE: ``` db.adminCommand( { setParameter: 1, waitForSecondaryBeforeNoopWriteMS: 20 } ) ``` ---------------------------------------- TITLE: Retrieve All Collection Information in MongoDB DESCRIPTION: This JavaScript example demonstrates how to use `db.getCollectionInfos()` to retrieve information for all collections within a specified database. It first switches to the 'example' database and then calls the method without any filters to get a list of all collections and their details. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/db.getCollectionInfos.txt#_snippet_1 LANGUAGE: javascript CODE: ``` use example db.getCollectionInfos() ``` ---------------------------------------- TITLE: Initialize MongoDB Replica Set with rs.initiate() Helper DESCRIPTION: Demonstrates how to assign a replica set configuration document to a variable and then use the `rs.initiate()` helper method to initialize the replica set. This example includes an arbiter member and notes on default port usage when omitted. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/replSetInitiate.txt#_snippet_3 LANGUAGE: javascript CODE: ``` config = { _id : "my_replica_set", members : [ {_id : 0, host : "rs1.example.net:27017"}, {_id : 1, host : "rs2.example.net:27017"}, {_id : 2, host : "rs3.example.net", arbiterOnly: true}, ] } rs.initiate(config) ``` ---------------------------------------- TITLE: Set replBatchLimitBytes at Startup and Runtime DESCRIPTION: Examples demonstrating how to configure the `replBatchLimitBytes` parameter to 64 MB, both when starting the `mongod` process and dynamically at runtime using the `setParameter` command in the MongoDB shell. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/parameters.txt#_snippet_149 LANGUAGE: javascript CODE: ``` mongod --setParameter replBatchLimitBytes=67108864 ``` LANGUAGE: bash CODE: ``` db.adminCommand( { setParameter: 1, replBatchLimitBytes: 64 * 1024 * 1024 } ) ``` ---------------------------------------- TITLE: JavaScript: Start Session with Causal Consistency and Retryable Writes DESCRIPTION: This example demonstrates how to start a new session using `Mongo.startSession()` with both `retryWrites` and `causalConsistency` enabled. The session is then associated with the global `db` variable, allowing subsequent operations to use these session settings. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/Mongo.startSession.txt#_snippet_1 LANGUAGE: javascript CODE: ``` db = db.getMongo().startSession({retryWrites: true, causalConsistency: true}).getDatabase(db.getName()); ``` ---------------------------------------- TITLE: Initialize MongoDB Replica Set with mlaunch DESCRIPTION: This shell command initializes a three-node MongoDB replica set using the `mtools`'s `mlaunch` utility. This setup is required to provide a suitable MongoDB environment for the Queryable Encryption tutorial. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/qe-tutorials/node/README.md#_snippet_0 LANGUAGE: sh CODE: ``` mlaunch init --replicaset --nodes 3 ``` ---------------------------------------- TITLE: Example Documents in config.shards Collection DESCRIPTION: JavaScript examples illustrating various document structures in the `config.shards` collection, including single shards, replica set shards, and shards with assigned zones. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/config-database.txt#_snippet_16 LANGUAGE: javascript CODE: ``` { "_id" : "shard0000", "host" : "localhost:30000", "state" : 1 } ``` LANGUAGE: javascript CODE: ``` { "_id" : "shard0001", "host" : "shard0001/localhost:27018,localhost:27019,localhost:27020", "state" : 1 } ``` LANGUAGE: javascript CODE: ``` { "_id" : "shard0002", "host" : "localhost:30002", "state" : 1, "tags": [ "NYC" ] } ``` ---------------------------------------- TITLE: Connect to MongoDB using mongosh Shell DESCRIPTION: Demonstrates how to connect to a MongoDB instance using the `mongosh` command-line shell, specifying authentication source, API version, and a username. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/connection-examples-by-language-onprem-standard-standalone.rst#_snippet_0 LANGUAGE: shell CODE: ``` mongosh "mongodb://@mongodb0.example.com:27017/?authSource=admin" --apiVersion 1 --username myDatabaseUser ``` ---------------------------------------- TITLE: MongoDB Slow Query Log Message with resolvedViews Example DESCRIPTION: An example of a MongoDB slow query log message (starting in 5.0) that includes the `resolvedViews` field, detailing the view's namespace, dependency chain, and resolved aggregation pipeline. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/log-messages.txt#_snippet_59 LANGUAGE: json CODE: ``` { "t": { "$date": "2021-09-30T17:53:54.646+00:00" }, "s": "I", "c": "COMMAND", "id": 51803, "ctx": "conn249", "svc": "R", "msg": "Slow query", "attr": { "type": "command", "ns": "test.myView", "appName": "MongoDB Shell", "command": { "find": "myView", "filter": {}, "lsid": { "id": { "$uuid": "ad176471-60e5-4e82-b977-156a9970d30f" } }, "$db": "test" }, "planSummary":"COLLSCAN", "resolvedViews": [ { "viewNamespace": "test.myView", "dependencyChain": [ "myView", "myCollection" ], "resolvedPipeline": [ { "$sort": { "firstName": 1 } } ] } ], "keysExamined": 0, "docsExamined": 1, "hasSortStage": true, "cursorExhausted": true, "numYields": 0, "nreturned": 1, "planCacheShapeHash": "3344645B", "planCacheKey": "1D3DE690", "queryFramework": "classic", "reslen": 134, "locks": { "ParallelBatchWriterMode": { "acquireCount": { "r": 1 } }, "ReplicationStateTransition": { "acquireCount": { "w": 1 } }, "Global": { "acquireCount": { "r": 4 } }, "Database": { "acquireCount": {"r": 1 } }, "Collection": { "acquireCount": { "r": 1 } }, "Mutex": { "acquireCount": { "r": 4 } } }, "storage": {}, "remote": "127.0.0.1:34868", "protocol": "op_msg", "workingMillis": 0, "durationMillis": 0 } } ``` ---------------------------------------- TITLE: JavaScript: Instantiate Mongo Connection and Get Database DESCRIPTION: This example demonstrates how to instantiate a new connection to a MongoDB instance and retrieve a reference to a specific database using the `Mongo.getDB()` method in JavaScript. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/Mongo.getDB.txt#_snippet_1 LANGUAGE: javascript CODE: ``` db = new Mongo().getDB("myDatabase"); ``` ---------------------------------------- TITLE: Navigate to MongoDB Server Bin Directory DESCRIPTION: Instructions for changing the current directory to the MongoDB Server `bin` directory, where the Compass installation scripts are located, for both Linux/macOS and Windows platforms. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/program/install_compass.txt#_snippet_0 LANGUAGE: bash CODE: ``` cd /bin ``` LANGUAGE: cmd CODE: ``` cd \bin ``` ---------------------------------------- TITLE: View Driver-Specific Code Examples DESCRIPTION: These snippets are placeholder comments indicating the active driver's code examples. They prompt the user to select a different driver from a dropdown menu to view actual code. SOURCE: https://github.com/mongodb/docs/blob/master/source/includes/tutorials/language-id-qe.rst#_snippet_0 LANGUAGE: java CODE: ``` // You are viewing the Java synchronous driver code examples. // Use the dropdown menu to select a different driver. ``` LANGUAGE: javascript CODE: ``` // You are viewing the Mongosh driver code examples. // Use the dropdown menu to select a different driver. ``` LANGUAGE: javascript CODE: ``` // You are viewing the Node.js driver code examples. // Use the dropdown menu to select a different driver. ``` LANGUAGE: python CODE: ``` # You are viewing the Python driver code examples. # Use the dropdown menu to select a different driver. ``` LANGUAGE: csharp CODE: ``` // You are viewing the C# driver code examples. // Use the dropdown menu to select a different driver. ``` LANGUAGE: go CODE: ``` // You are viewing the Golang driver code examples. // Use the dropdown menu to select a different driver. ``` ---------------------------------------- TITLE: Insert Documents for hint Example in MongoDB DESCRIPTION: Provides an example of inserting multiple documents into a 'members' collection. This setup is typically used to demonstrate the 'hint' option in subsequent delete operations, allowing for index selection during deletion. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/command/delete.txt#_snippet_8 LANGUAGE: javascript CODE: ``` db.members.insertMany([ { "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null }, { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }, { "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null }, { "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null } ]) ``` ---------------------------------------- TITLE: Start a MongoDB Session and Associate Database DESCRIPTION: This JavaScript example demonstrates how to initialize a new session using `db.getMongo().startSession()` and then reassign the global `db` variable to use the database associated with the newly created session via `session.getDatabase(db.getName())`. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/Session.txt#_snippet_1 LANGUAGE: javascript CODE: ``` var session = db.getMongo().startSession(); db = session.getDatabase(db.getName()); ``` ---------------------------------------- TITLE: MongoDB Bulk.find.deleteOne() Example: Create Collection DESCRIPTION: Provides a setup code snippet to create and populate a sample `music` collection in MongoDB using `db.music.insertMany()`. This collection serves as the dataset for demonstrating bulk operations. SOURCE: https://github.com/mongodb/docs/blob/master/source/reference/method/Bulk.find.deleteOne.txt#_snippet_2 LANGUAGE: javascript CODE: ``` db.music.insertMany( [ { artist: "DOA", genre: "punk" }, { artist: "Rick Astley", genre: "pop" }, { artist: "Black Flag", genre: "punk" }, { artist: "Justin Bieber", genre: "pop" } ] ) ``` ---------------------------------------- TITLE: Start MongoDB Config Server via Command Line DESCRIPTION: Starts a MongoDB `mongod` instance configured as a config server replica set member using command line arguments. This command is applicable for both initial setup and during an upgrade process after binary replacement. It specifies the replica set name, port, database path, and bind IP addresses. SOURCE: https://github.com/mongodb/docs/blob/master/source/release-notes/6.0-upgrade-sharded-cluster.txt#_snippet_5 LANGUAGE: bash CODE: ``` mongod --configsvr --replSet --port --dbpath --bind_ip localhost, ```