The following document lists the available methods in the MongoDB Shell. Click a method to see its documentation in the MongoDB Manual, including syntax and examples.
ImportantMethods which reset the shell's connection to the server trigger a termination of all open server sessions. When a session ends, all in-progress operations are terminated as well, and the client must re-authenticate if authentication is enabled.
The following methods reset the shell's connection:
db.auth
Mongo.setReadPref
Mongo.setReadConcern
Atlas Search indexes let you query data in Atlas Search. Atlas Search indexes enable performant text search queries by mapping search terms to the documents that contain those terms.
Use the following methods to manage Atlas Search indexes.
ImportantThe following methods can only be run on deployments hosted on MongoDB Atlas.
Method
Description
JavaScript constructor to instantiate a database connection from the mongo
shell or from a JavaScript file.
The Mongo()
method has the following parameters:
Parameter
Type
Description
host
string
Optional
The connection string for the target database connection.
If omitted, Mongo()
instantiates a connection to the localhost interface on the default port 27017
.
autoEncryptionOpts
Document
Optional
New in version 4.2.
Configuration parameters for enabling Client-Side Field Level Encryption.
autoEncryptionOpts
overrides the existing client-side field level encryption configuration of the database connection. If omitted, Mongo()
inherits the client-side field level encryption configuration of the current database connection.
For documentation of usage and syntax, see AutoEncryptionOpts.
Returns a database object.
Sets the read preference for the MongoDB connection.
Opens a change stream cursor for a replica set or a sharded cluster to report on all its non-system collections across its databases, with the exception of the admin
, local
, and config
databases.
Method
Description
Adds special wire protocol flags that modify the behavior of the query.
Allows db.collection.find()
operations against a sharded collection to return partial results, rather than an error, if one or more queried shards are unavailable.
Specifies the maximum number of documents MongoDB can return to the client within each batch returned in a query result. By default, the initial batch size is the lesser of 101
documents or 16 mebibytes (MiB) worth of documents. Subsequent batches have a maximum size of 16 MiB. This option can enforce a smaller limit than 16 MiB, but not a larger one. When set, the batchSize
is the lesser of batchSize
documents or 16 MiB worth of documents.
A batchSize
of 0
means that the cursor is established, but no documents are returned in the first batch.
The following example query returns results in batches of 100:
db.myCollection.find().batchSize(100)
Close a cursor and free associated server resources.
Specifies the collation for the cursor returned by the db.collection.find()
.
Attaches a comment to the query to allow for traceability in the logs and the system.profile collection.
Modifies the cursor to return the number of documents in the result set rather than the documents themselves.
Reports on the query execution plan for a cursor.
Applies a JavaScript function for every document in a cursor.
Returns true
if the cursor has documents and can be iterated.
Forces MongoDB to use a specific index for a query.
Returns true
if the cursor is closed.
Returns true
if the cursor is closed and there are no objects remaining in the batch.
Computes the total number of documents in the cursor client-side by fetching and iterating the result set.
Constrains the size of a cursor's result set.
Applies a function to each document in a cursor and collects the return values in an array.
Specifies an exclusive upper index bound for a cursor. For use with cursor.hint()
Specifies a cumulative time limit in milliseconds for processing operations on a cursor.
Specifies an inclusive lower index bound for a cursor. For use with cursor.hint()
Returns the next document in a cursor.
Instructs the server to avoid closing a cursor automatically after a period of inactivity.
Returns the number of documents left in the current cursor batch.
Specifies a read concern for a db.collection.find()
operation.
Specifies a read preference to a cursor to control how the client directs queries to a replica set.
Modifies the cursor to return index keys rather than the documents.
Adds an internal storage engine ID field to each document returned by the cursor.
Returns a count of the documents in the cursor after applying skip()
and limit()
methods.
Returns a cursor that begins returning results only after passing or skipping a number of documents.
Returns results ordered according to a sort specification.
Marks the cursor as tailable. Only valid for cursors over capped collections.
Returns an array that contains all documents returned by the cursor.
Note LimitationsAutomatic encryption is only available when mongosh
is connected to an Atlas cluster or a MongoDB Enterprise Server. For details, see Automatic Client-Side Field Level Encryption. The methods listed in this section are used for manual encryption, and are supported on non-enterprise servers.
Automatic encryption is not available with the Homebrew installation of mongosh
.
Field level encryption is only available in the mongosh
binary, and not available in the embedded Compass shell.
Method
Description
ClientEncryption.createEncryptedCollection()
Creates a collection with encrypted fields.
Decrypts the specified encryptedValue
if the current database connection was configured with access to the Key Management Service (KMS) and key vault used to encrypt encryptedValue
.
Encrypts the specified value using the specified encryptionKeyId
and encryptionAlgorithm
.
Returns the ClientEncryption
object for the current database collection.
Returns the KeyVault
object for the current database connection.
KeyVault.addKeyAlternateName()
Adds the keyAltName
to the keyAltNames
array of the data encryption key with the specified UUID.
Adds a data encryption key to the key vault associated to the database connection.
Deletes a data encryption key with the specified UUID from the key vault associated to the database connection.
Gets a data encryption key with the specified UUID. The data encryption key must exist in the key vault associated to the database connection.
Gets all data encryption keys with the specified keyAltName
.
Returns all data encryption keys stored in the key vault associated to the database connection.
KeyVault.removeKeyAlternateName()
Removes the specified keyAltName
from the data encryption key with the specified UUID. The data encryption key must exist in the key vault associated to the database connection.
Method
Description
buildInfo()
Returns the following JSON-formatted document that describes your mongosh
build and driver dependencies:
{ 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 }}
isInteractive()
Returns a boolean indicating whether mongosh is running in interactive or script mode.
load()
Loads and runs a JavaScript file in the shell.
In mongosh
, scripts loaded with the load()
method support the __filename
and __dirname
Node.js variables. These variables return the file name and directory of the loaded script, respectively. The returned values are always absolute paths.
The legacy mongo
shell cannot access a script's file name or directory in the load()
method.
print()
Print the specified text or variable. print()
and printjson()
are aliases for console.log()
.
> print("hello world")hello world> x = "example text"> print(x)example text
quit()
Exits the current shell session.
sleep()
Suspends the mongo
shell for a given period of time.
version()
Returns the current version of the mongosh
instance.
Method
Description
Adds a member to the replica set. You must connect to the primary of the replica set to run this method.
Adds an arbiter to an existing replica set.
Returns a document that contains the current replica set configuration.
Makes the replica set member that mongosh
is connected to ineligible to become primary for the specified duration. You must specify the duration in seconds.
Returns the status of the replica set from the oplog data.
Initializes a new replica set.
Returns the oplog of the replica set member that mongosh
is connected to.
Returns the oplog of the replica set member that mongosh
is connected to.
db.printSecondaryReplicationInfo
Returns the status of the secondary members of the replica set.
This is identical to the rs.printSecondaryReplicationInfo()
method.
The following is an example output from the rs.printSecondaryReplicationInfo()
method issued on a replica set with two secondary members:
source: rs2.example.net:27017{ syncedTo: 'Tue Oct 13 2020 09:37:28 GMT-0700 (Pacific Daylight Time)', replLag: '0 secs (0 hrs) behind the primary '}---source: rs3.example.net:27017{ syncedTo: 'Tue Oct 13 2020 09:37:28 GMT-0700 (Pacific Daylight Time)', replLag: '0 secs (0 hrs) behind the primary '}
rs.printSecondaryReplicationInfo
Returns the status of the secondary members of the replica set.
This is identical to the db.printSecondaryReplicationInfo()
method.
The following is an example output from the rs.printSecondaryReplicationInfo()
method issued on a replica set with two secondary members:
source: rs2.example.net:27017{ syncedTo: 'Tue Oct 13 2020 09:42:18 GMT-0700 (Pacific Daylight Time)', replLag: '0 secs (0 hrs) behind the primary '}---source: rs3.example.net:27017{ syncedTo: 'Tue Oct 13 2020 09:42:18 GMT-0700 (Pacific Daylight Time)', replLag: '0 secs (0 hrs) behind the primary '}
Modifies the configuration of an existing replica set.
Removes the member specified by hostname from the replica set.
Returns the status of the replica set member that mongosh
is connected to.
Makes the primary of the replica set a secondary. You must be connected to the primary to run this method.
Resets the sync target to the replica set member specified by hostname for the replica set member that mongosh
is connected to.
These methods configure whether mongosh
tracks anonymous telemetry data. Telemetry is enabled by default.
For more information on what data mongosh
tracks with telemetry, see Configure Telemetry Options.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4