### Snippet installation confirmation Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Example output showing the installation process and the prompt to load the newly installed snippet. ```javascript Running install... Installed new snippets analyze-schema. Do you want to load them now? [Y/n]: y Finished installing snippets: analyze-schema ``` -------------------------------- ### Example output of mongosh --build-info Source: https://www.mongodb.com/docs/mongodb-shell/install This is the output of the --build-info command, showing version, build architecture, platform, and dependency versions. It is useful for verifying your installation and checking for the security issue. ```javascript { "version": "2.5.8", "distributionKind": "packaged", "buildArch": "x64", "buildPlatform": "linux", "buildTarget": "unknown", "buildTime": "2025-09-09T10:18:30.614Z", "gitVersion": "7b6bd25a97ce617f8d5bfa26c36db6d99dc92419", "nodeVersion": "v24.9.0", "opensslVersion": "3.6.0", "sharedOpenssl": true, "runtimeArch": "x64", "runtimePlatform": "darwin", "runtimeGlibcVersion": "N/A", "deps": { "nodeDriverVersion": "6.19.0", "kerberosVersion": "2.2.2" } } ``` -------------------------------- ### Install and run analyze-schema snippet Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Install the 'analyze-schema' snippet and execute it against the 'reservations' collection. ```javascript snippet install analyze-schema schema(db.reservations) ``` -------------------------------- ### db.adminCommand.help() for method help Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Type db..help() to get help for a specific database method. This example returns help for db.adminCommand(). ```javascript db.adminCommand.help() ``` ```javascript db.adminCommand({ serverStatus: 1 }): Runs an arbitrary command against the admin database. For more information on usage: https://www.mongodb.com/docs/manual/reference/method/db.adminCommand ``` -------------------------------- ### Install a snippet package Source: https://www.mongodb.com/docs/mongodb-shell/snippets/packages Install a snippet package by name. Replace YOUR_NEW_SNIPPET with the actual snippet name. ```shell snippet install YOUR_NEW_SNIPPET ``` -------------------------------- ### Install gnupg if missing Source: https://www.mongodb.com/docs/mongodb-shell/install Installs gnupg and its required libraries when the previous key import fails with a gnupg error. ```sh sudo apt-get install gnupg ``` -------------------------------- ### db.serverCmdLineOpts() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Returns a document with information about the runtime options used to start the MongoDB instance. ```APIDOC ## db.serverCmdLineOpts() ### Description Returns a document with information about the runtime options used to start the MongoDB instance. ### Method GET ### Endpoint `db.serverCmdLineOpts()` ### Response #### Success Response Returns runtime options. #### Response Example ```json { "argv": [], "parsed": {} } ``` ``` -------------------------------- ### Install mongocompat snippet Source: https://www.mongodb.com/docs/mongodb-shell/reference/compatibility Use this command to install the mongocompat snippet, which provides access to legacy mongo shell APIs. ```shell snippet install mongocompat ``` -------------------------------- ### Install a snippet package Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Use this command to install a specific snippet package by name. ```javascript snippet install ``` -------------------------------- ### Verify mongosh installation with mongosh --version Source: https://www.mongodb.com/docs/mongodb-shell/install/?amazon-linux-version=None&debian-version=None&linux-distribution=None&macos-installation-method=None&operating-system=windows&rhel-version=None&ubuntu-version=None&windows-installation-method=msiexec Run this command in a command prompt to confirm that mongosh installed successfully. It returns the version of mongosh you installed. ```bash mongosh --version --- ``` -------------------------------- ### buildInfo() output example Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Shows the JSON document returned by buildInfo(), describing the mongosh build and driver dependencies. ```json { version: '1.10.1', distributionKind: 'packaged', buildArch: 'x64', buildPlatform: 'linux', buildTarget: 'unknown', buildTime: '2023-06-21T09:49:37.225Z', gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7', nodeVersion: 'v16.20.1', opensslVersion: '3.1.1', sharedOpenssl: true, runtimeArch: 'x64', runtimePlatform: 'darwin', deps: { nodeDriverVersion: '5.6.0', libmongocryptVersion: undefined, libmongocryptNodeBindingsVersion: undefined } } ``` -------------------------------- ### Example database and hostname prompt Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts The visual representation of the shell prompt showing the database name and hostname. ```javascript admin@centos0722:27502> ``` -------------------------------- ### BSON class help syntax Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Run .help() on either the class name or an instantiated instance to get a brief overview and a link with more information. ```none .help() // or ().help() ``` -------------------------------- ### Example Usage of mongocompat Snippet Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Demonstrates the legacy shell compatibility APIs provided by the mongocompat snippet. ```js > Array.sum([1, 2, 3]) 6 > tojsononeline({a:1,b:2,c:3}) { "a" : 1, "b" : 2, "c" : 3 } ``` -------------------------------- ### ObjectId class help examples Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Run either command to view help for the ObjectId BSON class. Both return the same output. ```javascript ObjectId.help() ``` ```javascript ObjectId().help() ``` -------------------------------- ### Create sales Collection for Examples Source: https://www.mongodb.com/docs/mongodb-shell/reference/ejson/serialize Inserts sample documents into the sales collection, including ISODate and Decimal128 types, to be used in the subsequent examples. ```javascript db.sales.insertMany( [ { custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60") }, { custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45") }, { custId: 486, purchaseDate: ISODate("2023-08-01"), quantity: 9, cost: Decimal128("200.53") } ] ) ``` -------------------------------- ### Install mongosh with Homebrew Source: https://www.mongodb.com/docs/mongodb-shell/install Run this command in the terminal to install the mongosh package using Homebrew. ```sh brew install mongosh ``` -------------------------------- ### Mongo.startSession() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Starts a session for the connection. ```APIDOC ## Mongo.startSession() ### Description Starts a session for the connection. ### Method Mongo.startSession() ### Endpoint Mongo.startSession() ``` -------------------------------- ### Create and Execute a Script to Connect and Insert Documents Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts This example demonstrates creating a script to connect to a local database and insert sample documents, followed by executing the script and verifying the results. ```javascript db = connect( 'mongodb://localhost/myDatabase' ); db.movies.insertMany( [ { title: 'Titanic', year: 1997, genres: [ 'Drama', 'Romance' ] }, { title: 'Spirited Away', year: 2001, genres: [ 'Animation', 'Adventure', 'Family' ] }, { title: 'Casablanca', genres: [ 'Drama', 'Romance', 'War' ] } ] ) ``` ```javascript load( "connect-and-insert.js" ) ``` ```javascript use myDatabase db.movies.find() ``` -------------------------------- ### npm installation warning Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Warning displayed during the first use of snippets if npm is not installed. ```javascript This operation requires downloading a recent release of npm. Do you want to proceed? [Y/n]: ``` -------------------------------- ### Example Document Structure Source: https://www.mongodb.com/docs/mongodb-shell/run-agg-pipelines A sample document from the movies collection in the sample_mflix dataset. ```javascript { _id: 573a1397f29313caabce8347, fullplot: 'In a cyberpunk vision of the future, man has developed the technology to create replicants, human clones used to serve in the colonies outside Earth but with fixed lifespans. In Los Angeles, 2019, Deckard is a Blade Runner, a cop who specializes in terminating replicants. Originally in retirement, he is forced to re-enter the force when four replicants escape from an off-world colony to Earth.', imdb: { rating: 8.2, votes: 419589, id: 83658 }, year: 1982, plot: 'A blade runner must pursue and try to terminate four replicants who stole a ship in space and have returned to Earth to find their creator.', genres: [ 'Sci-Fi', 'Thriller' ], rated: 'R', metacritic: 88, title: 'Blade Runner', lastupdated: '2015-09-04 00:05:51.990000000', languages: [ 'English', 'German', 'Cantonese', 'Japanese', 'Hungarian' ], writers: [ 'Hampton Fancher (screenplay)', 'David Webb Peoples (screenplay)', 'Philip K. Dick (novel)' ], type: 'movie', tomatoes: { viewer: { rating: 4, numReviews: 331213, meter: 91 }, dvd: 1997-08-27T00:00:00.000Z, critic: { rating: 8.5, numReviews: 102, meter: 90 }, lastUpdated: 2015-09-12T17:48:21.000Z, consensus: "Misunderstood when it first hit theaters, the influence of Ridley Scott's mysterious, neo-noir Blade Runner has deepened with time. A visually remarkable, achingly human sci-fi masterpiece.", rotten: 10, production: 'Warner Bros. Pictures', fresh: 92 }, poster: 'https://m.media-amazon.com/images/M/MV5BNzQzMzJhZTEtOWM4NS00MTdhLTg0YjgtMjM4MDRkZjUwZDBlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SY1000_SX677_AL_.jpg', num_mflix_comments: 1, released: 1982-06-25T00:00:00.000Z, awards: { wins: 13, nominations: 15, text: 'Nominated for 2 Oscars. Another 11 wins & 15 nominations.' }, countries: [ 'USA', 'Hong Kong', 'UK' ], cast: [ 'Harrison Ford', 'Rutger Hauer', 'Sean Young', 'Edward James Olmos' ], directors: [ 'Ridley Scott' ], runtime: 117 } ``` -------------------------------- ### Insert sample sales documents Source: https://www.mongodb.com/docs/mongodb-shell/reference/ejson/stringify Create a sales collection in the test database with sample documents. Required before trying the EJSON.stringify examples. ```javascript db.sales.insertMany( [ { custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60"), }, { custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45"), }, { custId: 486, purchaseDate: ISODate("2023-08-01"), quantity: 9, cost: Decimal128("200.53"), }, ] ) ``` -------------------------------- ### Show help for a specific collection method with db.collection.insertOne.help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Use `db...help()` to display help for a specific collection method. The example shows help for `db.collection.insertOne()`. ```javascript db.collection.insertOne.help() ``` ```none db.collection.insertOne(document, options): Inserts a document into a collection. For more information on usage: https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne ``` -------------------------------- ### Example code in built-in editor Source: https://www.mongodb.com/docs/mongodb-shell/reference/editor-mode An example of multi-line code input within the built-in editor mode. ```javascript // Entering editor mode (^D to finish, ^C to cancel) var albums = [ { "artist": "Beatles", "album": "Revolver" }, { "artist": "The Monkees", "album": "Head"} ] db.music.insertMany( albums ) ``` -------------------------------- ### Verify mongosh Installation with mongosh --build-info Source: https://www.mongodb.com/docs/mongodb-shell/install/upgrade/?linux-distribution=None&macos-installation-method=None&operating-system=windows&windows-installation-method=zip Run this command to confirm that the new mongosh binary is in your system PATH and that the upgrade was successful. ```bash mongosh --build-info --- ``` -------------------------------- ### Create MongoDB apt list file Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file for your Ubuntu version. The example uses 'focal' (Ubuntu 20.04) and supports amd64 and arm64 architectures. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.3 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Install mongosh with OpenSSL 1.1 Source: https://www.mongodb.com/docs/mongodb-shell/install Installs mongosh using your system's OpenSSL 1.1 libraries. ```sh sudo apt-get install -y mongodb-mongosh-shared-openssl11 ``` -------------------------------- ### Install mongosh with OpenSSL 1.1 libraries Source: https://www.mongodb.com/docs/mongodb-shell/install Run this command to install mongosh with your system's OpenSSL 1.1 libraries. ```sh sudo yum install -y mongodb-mongosh-shared-openssl11 ``` -------------------------------- ### List installed snippets with snippet ls Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets The `snippet ls` command returns a list of locally installed snippets along with some version and source information. The output shows the snippets directory and each snippet with its source and version. ```shell snippets@ /root/.mongodb/mongosh/snippets ├── mongosh:PRIVATE..DecryptCards@1.0.5 ├── mongosh:analyze-schema@1.0.5 └── npm@7.23.0 ``` -------------------------------- ### Install mongosh with included OpenSSL Source: https://www.mongodb.com/docs/mongodb-shell/install Installs the latest stable version of mongosh with its bundled OpenSSL libraries. ```sh sudo apt-get install -y mongodb-mongosh ``` -------------------------------- ### Install latest stable mongosh with included OpenSSL Source: https://www.mongodb.com/docs/mongodb-shell/install Run this command to install the latest stable version of mongosh with the included OpenSSL libraries. ```sh sudo yum install -y mongodb-mongosh ``` -------------------------------- ### Install mongosh with included OpenSSL libraries Source: https://www.mongodb.com/docs/mongodb-shell/install Installs the latest stable version of mongosh with the included OpenSSL libraries. ```sh sudo yum install -y mongodb-mongosh ``` -------------------------------- ### Install mongosh with OpenSSL 3.0 libraries Source: https://www.mongodb.com/docs/mongodb-shell/install Run this command to install mongosh with your system's OpenSSL 3.0 libraries. ```sh sudo yum install -y mongodb-mongosh-shared-openssl3 ``` -------------------------------- ### Install mongosh with OpenSSL 1.1 libraries Source: https://www.mongodb.com/docs/mongodb-shell/install Installs mongosh using your system's OpenSSL 1.1 libraries. ```sh sudo yum install -y mongodb-mongosh-shared-openssl11 ``` -------------------------------- ### Start MongoDB Shell and Display Log ID Source: https://www.mongodb.com/docs/mongodb-shell/logs/view Shows the output when starting the MongoDB Shell, including the log ID displayed at startup. ```javascript $ mongosh Current Mongosh Log ID: c2961dbd6b73b052671d9df0 Connecting to: mongodb://127.0.0.1:27017 Using MongoDB: 4.2.8 Using Mongosh: 2.13.0 ``` -------------------------------- ### Display schema analysis output Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Example output showing the schema structure of a collection. ```js > schema(db.coll); ┌─────────┬───────┬───────────┬────────────┐ │ (index) │ 0 │ 1 │ 2 │ ├─────────┼───────┼───────────┼────────────┤ │ 0 │ '_id' │ '100.0 %' │ 'ObjectID' │ │ 1 │ 'a ' │ '50.0 %' │ 'Number' │ │ 2 │ 'a ' │ '50.0 %' │ 'String' │ └─────────┴───────┴───────────┴────────────┘ ``` -------------------------------- ### Get Help for a Snippet Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Displays the README file for a specific snippet to understand its interface and usage. ```javascript snippet help mongocompat ``` -------------------------------- ### Create MongoDB apt source list file Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file for your Ubuntu version. The example uses bionic (Ubuntu 18.04) but should be adjusted for your version. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/8.3 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Create MongoDB apt source list Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file for Ubuntu (example uses jammy). Adjust the codename for your Ubuntu version. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.3 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Session.startTransaction() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Starts a multi-document transaction associated with the session. ```APIDOC ## Session.startTransaction() ### Description Starts a multi-document transaction associated with the session. ### Method Session.startTransaction() ### Endpoint Session.startTransaction() ``` -------------------------------- ### Example mongosh configuration file Source: https://www.mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-global Sets displayBatchSize to 50, inspectDepth to 20, and redactHistory to 'remove-redact' in a YAML configuration file. ```yaml mongosh: displayBatchSize: 50 inspectDepth: 20 redactHistory: "remove-redact" ``` -------------------------------- ### print() usage example Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Shows how to use print() to output text and variables. print() is an alias for console.log(). ```javascript > print("hello world") hello world > x = "example text" > print(x) example text ``` -------------------------------- ### Get Repository Information Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Displays the homepage and URL for each snippet repository. ```javascript snippet info ``` ```javascript Snippet repository URL: https://compass.mongodb.com/mongosh/snippets-index.bson.br --> Homepage: https://github.com/mongodb-labs/mongosh-snippets ``` -------------------------------- ### Example client connection log document Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts The document format added to the clientConnections collection upon database connection. ```javascript { _id: ObjectId("61d4bbf0fa4c85f53418070f"), connectTime: ISODate("2022-01-04T21:28:16.367Z") } ``` -------------------------------- ### Start the built-in editor Source: https://www.mongodb.com/docs/mongodb-shell/reference/editor-mode Use the .editor command to open the built-in multiline editor. Press + d to exit and execute the code. ```javascript .editor ``` -------------------------------- ### Configure yum repository for mongosh Source: https://www.mongodb.com/docs/mongodb-shell/install Create the /etc/yum.repos.d/mongodb-org-8.3.repo file with this content to set up the MongoDB repository for yum. This is required before installing mongosh. ```none [mongodb-org-8.3] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/10/mongodb-org/8.3/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc ``` -------------------------------- ### rs.initiate() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Initializes a new replica set. ```APIDOC ## rs.initiate() ### Description Initializes a new replica set. ### Method rs.initiate() ### Parameters None documented. ### Response No documented response. ``` -------------------------------- ### OpenSSL configuration error on RHEL 9+ Source: https://www.mongodb.com/docs/mongodb-shell/install If mongosh fails to start with this OpenSSL error on RHEL 9+ or derivatives like Amazon Linux 2023, install the mongodb-mongosh-shared-openssl3 package. ```none mongosh: OpenSSL configuration error: ...:error:030000A9:digital envelope routines:alg_module_init:unknown option:../deps/openssl/openssl/crypto/evp/evp_cnf.c:61:name=rh-allow-sha1-signatures, value=yes ``` -------------------------------- ### Uninstall a snippet with snippet uninstall Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Use the `snippet uninstall` command to remove a snippet. If you are unsure of the name, the `snippet ls` command lists all installed snippets. This example uninstalls the `analyze-schema` snippet. ```javascript snippet uninstall analyze-schema ``` -------------------------------- ### Set logRetentionGB in a configuration file Source: https://www.mongodb.com/docs/mongodb-shell/logs/retention/size Example configuration file snippet to set the maximum log storage size to 3.5 GB. ```yaml mongosh: logRetentionGB: 3.5 ``` -------------------------------- ### Import MongoDB public GPG key Source: https://www.mongodb.com/docs/mongodb-shell/install Downloads and installs the MongoDB public GPG key to /etc/apt/trusted.gpg.d/server-8.0.asc. The key is displayed in the terminal; no need to save it manually. ```sh wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc ``` -------------------------------- ### Configuration file setting inspectDepth to 20 Source: https://www.mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-api YAML configuration file that sets the inspectDepth setting to 20. This is used as the starting point in the example showing how config API settings override file settings. ```yaml mongosh: inspectDepth: 20 ``` -------------------------------- ### sh.startBalancer() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Enables the balancer. ```APIDOC ## sh.startBalancer() ### Description Enables the balancer. ### Method Shell method ### Endpoint sh.startBalancer() ### Parameters None documented in source. ### Response No response details documented in source. ``` -------------------------------- ### Get Current Log File Path with log.getPath() Source: https://www.mongodb.com/docs/mongodb-shell/logs/view Shows the log.getPath() command to view the current log file location and an example output. The hexadecimal value in the path is the log identifier for the current session. ```javascript log.getPath() ``` ```javascript /Users/jane.doe/.mongodb/mongosh/c2961dbd6b73b052671d9df0_log ``` -------------------------------- ### Get help for a snippet Source: https://www.mongodb.com/docs/mongodb-shell/snippets/working-with-snippets Use the 'snippet help' command to view the functionality and usage instructions for a specific snippet. ```javascript testDB> snippet help analyze-schema # analyze-schema Analyze the schema of a collection or a cursor. ``` -------------------------------- ### Run script with mongosh --file Source: https://www.mongodb.com/docs/mongodb-shell/logs/custom-entries Runs the script programmatically by using the --file option when starting mongosh. ```sh mongosh --file connect-and-insert-with-log-entry.js ``` -------------------------------- ### Create /etc/yum.repos.d/mongodb-org-8.3.repo Source: https://www.mongodb.com/docs/mongodb-shell/install Configuration file for the MongoDB yum repository. Required before installing mongosh. The baseurl uses the Red Hat 9 repository path. ```none [mongodb-org-8.3] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.3/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc ``` -------------------------------- ### Example Aggregation Pipeline Source: https://www.mongodb.com/docs/mongodb-shell/run-agg-pipelines A four-stage aggregation pipeline that projects fields, unwinds genres, calculates average ratings per genre, and sorts the results. ```javascript db.movies.aggregate([ // First Stage { $project: { _id: 0, genres: 1, imdb: 1, title: 1 } }, // Second Stage { $unwind: "$genres" }, // Third Stage { $group: { _id: "$genres", averageGenreRating: { $avg: "$imdb.rating" } } }, // Fourth Stage { $sort: { averageGenreRating: -1 } } ] ) ``` -------------------------------- ### Install mongosh with OpenSSL 3.0 Source: https://www.mongodb.com/docs/mongodb-shell/install Installs mongosh using your system's OpenSSL 3.0 libraries. ```sh sudo apt-get install -y mongodb-mongosh-shared-openssl3 ``` -------------------------------- ### db.help() to list database methods Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Run db.help() to see the list of database methods available on the db object. The output resembles the abbreviated list shown. ```javascript db.help() ``` ```none Database Class: getMongo Returns the current database connection getName Returns the name of the DB getCollectionNames Returns an array containing the names of all collections in the current database. getCollectionInfos Returns an array of documents with collection information, i.e. collection name and options, for the current database. runCommand Runs an arbitrary command on the database. adminCommand Runs an arbitrary command against the admin database. ... ``` -------------------------------- ### .help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Provides a brief overview of a BSON class and a link with more information. Can be called on the class name or an instantiated instance. ```APIDOC ## .help() ### Description Provides a brief overview of a BSON class and a link with more information. Can be called on the class name or an instantiated instance. ### Method help() ### Endpoint N/A (Shell method) ### Parameters None ### Request Example ```javascript ObjectId.help() // or ObjectId().help() ``` ### Response #### Success Response Returns a description of the BSON class and a link to more information. #### Response Example ```javascript The ObjectId BSON Class: For more information on usage: https://mongodb.github.io/node-mongodb-native/3.6/api/ObjectID.html ``` ``` -------------------------------- ### Show additional details for a collection method with db.collection.insertOne Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Type the method name without parentheses to see additional details. The example returns details about the `insertOne()` method. ```javascript db.collection.insertOne ``` ```javascript [Function: insertOne] AsyncFunction { apiVersions: [ 1, Infinity ], serverVersions: [ '3.2.0', '999.999.999' ], returnsPromise: true, topologies: [ 'ReplSet', 'Sharded', 'LoadBalanced', 'Standalone' ], returnType: { type: 'unknown', attributes: {} }, deprecated: false, platforms: [ 0, 1, 2 ], isDirectShellCommand: false, acceptsRawInput: false, shellCommandCompleter: undefined, help: [Function (anonymous)] Help } ``` -------------------------------- ### Command Line EJSON.serialize() Example Saving to File Source: https://www.mongodb.com/docs/mongodb-shell/reference/ejson/serialize Uses mongosh --eval to serialize the sales collection and redirects output to sales.json. The command is formatted with line continuations for readability. ```shell # Note: The example is formatted to fit the page. mongosh --quiet \ --eval "EJSON.serialize( db.sales.find().toArray() )" \ > sales.json ``` -------------------------------- ### Install mongosh with OpenSSL 3.0 libraries Source: https://www.mongodb.com/docs/mongodb-shell/install Installs mongosh using your system's OpenSSL 3.0 libraries. ```sh sudo yum install -y mongodb-mongosh-shared-openssl3 ``` -------------------------------- ### Create MongoDB apt source list file Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the list file /etc/apt/sources.list.d/mongodb-org-8.3.list for Debian, adding the MongoDB repository for trixie. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian trixie/mongodb-org/8.3 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Create registry index with make-index.js Source: https://www.mongodb.com/docs/mongodb-shell/snippets/packages Run this command from the mongo-snippets directory to create the registry index file. The output is a brotli-compressed index.bson.br file. ```shell node ./scripts/make-index.js ``` -------------------------------- ### Minimal package.json for a MongoDB Shell snippet Source: https://www.mongodb.com/docs/mongodb-shell/snippets/packages A minimal package.json file with required fields: name, snippetName, version, description, main, license, and publishConfig. The snippetName is used with commands like install. The description should be kept under 50-60 characters to avoid display issues. ```typescript { "name": "@mongosh/snippet-resumetoken", "snippetName": "resumetoken", "version": "1.0.2", "description": "Resume token decoder script", "main": "index.js", "license": "Apache-2.0", "publishConfig": { "access": "public" } } ``` -------------------------------- ### Connect with Authentication using --username and --authenticationDatabase Source: https://www.mongodb.com/docs/mongodb-shell/connect Use this command to connect to a MongoDB deployment that requires authentication. mongosh prompts for the password, which is hidden as you type. The example authenticates as user 'alice' on the 'admin' database. ```sh mongosh "mongodb://mongodb0.example.com:28015" --username alice --authenticationDatabase admin ``` -------------------------------- ### Format Output with EJSON.stringify Built-in Formatting Source: https://www.mongodb.com/docs/mongodb-shell/reference/options This command uses EJSON's built-in formatting options to produce output formatted the same as the previous example, potentially eliminating the need for jq. ```javascript mongosh --quiet --host rs0/centos1104 --port 27500 \ --eval "EJSON.stringify( rs.status().members.map( \ ({ _id, name, stateStr }) => ({ _id, name, stateStr })), null, 2);" ``` -------------------------------- ### Import salesDeserialize.json from command line Source: https://www.mongodb.com/docs/mongodb-shell/reference/ejson/deserialize Imports the previously created JSON file and populates a new collection named salesFromDeserializeFile. ```sh # Note: The example is formatted to fit the page. mongosh --quiet --eval "db.salesFromDeserializeFile.insertMany( \ EJSON.deserialize( JSON.parse ( \ fs.readFileSync( 'salesDeserialize.json', 'utf8' ) ) ) )" ``` -------------------------------- ### Show collection methods with db.collection.help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Use `db..help()` to see the list of methods available on collection objects. The `` can be the name of an existing or non-existent collection. ```javascript db.collection.help() ``` ```none Collection Class: aggregate Calculates aggregate values for the data in a collection or a view. bulkWrite Performs multiple write operations with controls for order of execution. count Returns the count of documents that would match a find() query for the collection or view. countDocuments Returns the count of documents that match the query for a collection or view. deleteMany Removes all documents that match the filter from a collection. deleteOne Removes a single document from a collection. ... ``` -------------------------------- ### View Build Information with mongosh --build-info Source: https://www.mongodb.com/docs/mongodb-shell/reference/options Run this command to display JSON-formatted build information and driver dependencies for the mongosh binary. ```sh mongosh --build-info ``` ```javascript { version: '1.10.1', distributionKind: 'packaged', buildArch: 'x64', buildPlatform: 'linux', buildTarget: 'unknown', buildTime: '2023-06-21T09:49:37.225Z', gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7', nodeVersion: 'v16.20.1', opensslVersion: '3.1.1', sharedOpenssl: true, runtimeArch: 'x64', runtimePlatform: 'darwin', deps: { nodeDriverVersion: '5.6.0' } } ``` -------------------------------- ### Numeric Types Collection Example Source: https://www.mongodb.com/docs/mongodb-shell/reference/data-types Sample documents for the 'types' collection used in the numeric type query examples. Each document has a value and an expectedType field. ```javascript { _id: 1, value: 1, expectedType: 'Int32' }, { _id: 2, value: Long("1"), expectedType: 'Long' }, { _id: 3, value: 1.01, expectedType: 'Double' }, { _id: 4, value: Decimal128("1.01"), expectedType: 'Decimal128' }, { _id: 5, value: 3200000001, expectedType: 'Double' } ``` -------------------------------- ### Start New Editing Session Source: https://www.mongodb.com/docs/mongodb-shell/reference/editor-mode Invokes the 'edit' command without arguments to start a new editing session, which opens with the last edit loaded. ```javascript edit ``` -------------------------------- ### mongosh --help command line option Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Use this command to see the options for running the mongosh executable and connecting to a deployment. ```bash mongosh --help ``` -------------------------------- ### Switch Database Command Source: https://www.mongodb.com/docs/mongodb-shell/run-agg-pipelines Command to switch to the sample_mflix database before running aggregation queries. ```javascript use sample_mflix ``` -------------------------------- ### sh.startAutoMerger() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Enables the AutoMerger. New in version 7.0. ```APIDOC ## sh.startAutoMerger() ### Description Enables the AutoMerger. New in version 7.0. ### Method Shell method ### Endpoint sh.startAutoMerger() ### Parameters None documented in source. ### Response No response details documented in source. ``` -------------------------------- ### KeyVault.getKeyByAltName() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Gets all data encryption keys with the specified keyAltName. ```APIDOC ## KeyVault.getKeyByAltName() ### Description Gets all data encryption keys with the specified keyAltName. ### Method KeyVault.getKeyByAltName() ### Parameters - **keyAltName** (unknown) - Required - The alternate name to search for. ### Response Returns all data encryption keys with the specified keyAltName. ``` -------------------------------- ### db.hello() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Returns a document describing the role of the mongod instance, including primary/secondary status in a replica set. ```APIDOC ## db.hello() ### Description Returns a document that describes the role of the mongod instance. If the mongod is a member of a replica set, the isWritablePrimary and secondary fields report if the instance is the primary or a secondary member. ### Method GET ### Endpoint `db.hello()` ### Response #### Success Response - **isWritablePrimary** (boolean) - Indicates if the instance is the primary. - **secondary** (boolean) - Indicates if the instance is a secondary. #### Response Example ```json { "isWritablePrimary": true, "secondary": false } ``` ``` -------------------------------- ### Class method alternative for database operation Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts/considerations Shows a class with an init() method that performs the database operation, as an alternative to async JavaScript. To use, construct a class instance then call the .init() method. ```text class FindResults { constructor() { } init() { this.value = db.students.find(); } } ``` -------------------------------- ### cursor.explain() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Reports on the query execution plan for a cursor. ```APIDOC ## cursor.explain() ### Description Reports on the query execution plan for a cursor. ### Method cursor.explain() ### Endpoint cursor.explain() ### Parameters No parameters documented. ### Response No response documented. ``` -------------------------------- ### JavaScript Setter Limitation Source: https://www.mongodb.com/docs/mongodb-shell/reference/compatibility This example shows a class setter pattern that does not work in mongosh. ```javascript // This code will fail class TestClass { value = 1; get property() { return this.value; } // does not work: set property(value) { this.value = db.test.findOne({ value }); } } ``` -------------------------------- ### history() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Displays a list of previously executed commands. Available starting in MongoDB Shell 2.4.0. ```APIDOC ## history() ### Description Displays a list of previously executed commands. Available starting in MongoDB Shell 2.4.0. ### Method history() ### Endpoint N/A (Shell method) ### Parameters None ### Request Example history() ### Response #### Success Response Displays a list of previously executed commands. #### Response Example N/A ``` -------------------------------- ### Create MongoDB apt source list Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file for Ubuntu Noble (24.04) with amd64 and arm64 architectures. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.3 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Connect using TLS with connection string option Source: https://www.mongodb.com/docs/mongodb-shell/connect Enable TLS by setting the tls option to true in the connection string. ```sh mongosh "mongodb://mongodb0.example.com:28015/?tls=true" ``` -------------------------------- ### db.commandHelp() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Displays help text for the specified database command. ```APIDOC ## db.commandHelp() ### Description Displays help text for the specified database command. ### Method commandHelp ### Endpoint db.commandHelp() ``` -------------------------------- ### Refresh snippet metadata Source: https://www.mongodb.com/docs/mongodb-shell/snippets/packages Run this command in mongosh to refresh the snippet metadata before installing a new snippet. ```shell snippet refresh ``` -------------------------------- ### log.help() - Display log method help Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Run this command in mongosh to see available log message methods. ```javascript log.help() ``` -------------------------------- ### Switch databases with use Source: https://www.mongodb.com/docs/mongodb-shell/run-commands Issue the `use ` helper to switch databases. Replace `` with the target database name. ```javascript use ``` -------------------------------- ### db..help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Displays help on collection methods. The can be the name of an existing collection or a non-existing collection. ```APIDOC ## db..help() ### Description Displays help on collection methods. The can be the name of an existing collection or a non-existing collection. ### Method db..help() ### Endpoint N/A (Shell method) ### Parameters #### Path Parameters - **collection** (string) - Required - The name of the collection. ### Request Example db.myCollection.help() ### Response #### Success Response Displays help text for collection methods. #### Response Example N/A ``` -------------------------------- ### Array Sort Failure in mongosh Source: https://www.mongodb.com/docs/mongodb-shell/reference/compatibility This example demonstrates an unsupported array sort pattern that fails in mongosh. ```javascript // This code will fail db.getCollectionNames().sort( ( collectionOne, collectionTwo ) => { return db[ collectionOne ].estimatedDocumentCount() - db[ collectionOne ].estimatedDocumentCount() ) } ); ``` -------------------------------- ### Failing Non-Async Generator Functions Source: https://www.mongodb.com/docs/mongodb-shell/reference/compatibility Examples of generator functions that fail when yielding database query results. ```javascript // This code will fail function* FindResults() { yield db.students.findOne(); } // This code will fail function listEntries() { return db.students.findOne(); } function* findResults() { yield listEntries(); } ``` -------------------------------- ### PlanCache.help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Lists the methods available to view and modify a collection’s query plan cache. ```APIDOC ## PlanCache.help() ### Description Lists the methods available to view and modify a collection’s query plan cache. ### Method GET ### Endpoint `PlanCache.help()` ### Parameters None ### Response #### Success Response Returns a list of available methods. #### Response Example ``` List of methods ``` ``` -------------------------------- ### Class Initialization Method Alternative Source: https://www.mongodb.com/docs/mongodb-shell/reference/compatibility Defining an explicit init method to perform database operations after class instantiation. ```text class FindResults { constructor() { } init() { this.value = db.students.find(); } } ``` -------------------------------- ### Example mongosh prompt with line numbers Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts The visual representation of the shell prompt after applying the line number configuration. ```javascript 1> show collections 2> use test 3> ``` -------------------------------- ### Create MongoDB apt source list file Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file for Debian (bookworm) with the MongoDB repository for version 8.3, supporting amd64 and arm64 architectures. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.3 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Reloaded example code for editing Source: https://www.mongodb.com/docs/mongodb-shell/reference/editor-mode The code is reformatted when reloaded into the editor, making it easier to identify the syntax error. ```javascript // WARNING: This code contains an error db.users.insertMany([{ "name": "Joey", "group": "sales" } { "name": "Marie", "group": "sales" }, { "name": "Elton", "group": "accounting" }, { "name": "Paola", "group": "marketing" } ]) ``` -------------------------------- ### Create MongoDB apt list file Source: https://www.mongodb.com/docs/mongodb-shell/install Creates the /etc/apt/sources.list.d/mongodb-org-8.3.list file with the MongoDB repository for Debian bullseye, supporting amd64 and arm64 architectures. ```sh echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bullseye/mongodb-org/8.3 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list ``` -------------------------------- ### Successful key import output Source: https://www.mongodb.com/docs/mongodb-shell/install/verify-signatures/rpm Expected output when the key imports successfully for the first time. ```sh gpg: key CEED0419D361CB16: public key "Mongosh Release Signing Key " imported gpg: Total number processed: 1 gpg: imported: 1 ``` -------------------------------- ### Custom log entry output Source: https://www.mongodb.com/docs/mongodb-shell/logs/custom-entries Example of the custom log entry that appears in the session logs after running the script. ```javascript {"t":{"$date":"2025-02-25T18:04:01.690Z"},"s":"I","c":"MONGOSH-SCRIPTS","id":1000000054,"ctx":"custom-log","msg":"InsertData: Inserted 3 movies"} ``` -------------------------------- ### Connect using TLS with command-line option Source: https://www.mongodb.com/docs/mongodb-shell/connect Enable TLS by specifying the --tls command-line option when connecting to a remote host. ```sh mongosh "mongodb://mongodb0.example.com:28015" --tls ``` -------------------------------- ### Load environment variables and connect to MongoDB in myScript.js Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts/env-variables Create a `myScript.js` file in the same directory as your `.env` file. The script uses `loadEnvFile()` from `node:process` to load environment variables, then connects to MongoDB using `process.env.MONGODB_URI` and prints the database name. ```javascript // Load environment variables from the .env file const { loadEnvFile } = require('node:process'); loadEnvFile(); // Connect to the MongoDB database db = connect(process.env.MONGODB_URI); // Confirm the connection by printing the database name console.log(db); ``` -------------------------------- ### Use connect() to connect to a MongoDB instance Source: https://www.mongodb.com/docs/mongodb-shell/write-scripts Use the connect() method to connect to a specific host and port while simultaneously setting the global db variable. ```javascript db = connect("localhost:27020/myDatabase"); ``` -------------------------------- ### Example code with a syntax error Source: https://www.mongodb.com/docs/mongodb-shell/reference/editor-mode This snippet contains a syntax error due to a missing comma, which can be corrected using the edit command. ```javascript // WARNING: This code contains an error db.users.insertMany( [ { "name": "Joey", "group": "sales" } { "name": "Marie", "group": "sales" }, { "name": "Elton", "group": "accounting" }, { "name": "Paola", "group": "marketing" } ] ) ``` -------------------------------- ### db.help() Source: https://www.mongodb.com/docs/mongodb-shell/reference/access-mdb-shell-help Displays help for database methods in the MongoDB Shell. ```APIDOC ## db.help() ### Description Displays help for database methods available in the MongoDB Shell. ### Method db.help() ### Endpoint N/A (Shell method) ### Parameters None ### Request Example db.help() ### Response #### Success Response Displays help text for database methods. #### Response Example N/A ``` -------------------------------- ### db.serverBuildInfo() Source: https://www.mongodb.com/docs/mongodb-shell/reference/methods Returns a document that displays the compilation parameters for the mongod instance. ```APIDOC ## db.serverBuildInfo() ### Description Returns a document that displays the compilation parameters for the mongod instance. ### Method GET ### Endpoint `db.serverBuildInfo()` ### Response #### Success Response Returns compilation parameters. #### Response Example ```json { "version": "", "gitVersion": "", "compilerFlags": "" } ``` ```