Methods (original) (raw)
The following document lists the available methods in the MongoDB Shell. Click a method to see its documentation in theMongoDB Manual, including syntax and examples.
Important
Methods 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.
Important
The following methods can only be run on deployments hosted onMongoDB Atlas.
Method | Description |
---|---|
Mongo() | JavaScript constructor to instantiate a database connection from the mongo shell or from a JavaScript file.The Mongo() method has the following parameters:ParameterTypeDescriptionhoststring_Optional_The connection string for the target database connection.If omitted, Mongo() instantiates a connection to the localhost interface on the default port 27017.autoEncryptionOptsDocument_Optional_ New in version 4.2.Configuration parameters for enablingClient-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, seeAutoEncryptionOpts. |
Mongo.getDB() | Returns a database object. |
Mongo.setReadPref() | Sets the read preference for the MongoDB connection. |
Mongo.watch() | 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 |
---|---|
cursor.addOption() | Adds special wire protocol flags that modify the behavior of the query. |
cursor.allowPartialResults() | 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. |
cursor.batchSize() | 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, thebatchSize 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) |
cursor.close() | Close a cursor and free associated server resources. |
cursor.collation() | Specifies the collation for the cursor returned by thedb.collection.find(). |
cursor.comment() | Attaches a comment to the query to allow for traceability in the logs and the system.profile collection. |
cursor.count() | Modifies the cursor to return the number of documents in the result set rather than the documents themselves. |
cursor.explain() | Reports on the query execution plan for a cursor. |
cursor.forEach() | Applies a JavaScript function for every document in a cursor. |
cursor.hasNext() | Returns true if the cursor has documents and can be iterated. |
cursor.hint() | Forces MongoDB to use a specific index for a query. |
cursor.isClosed() | Returns true if the cursor is closed. |
cursor.isExhausted() | Returns true if the cursor is closed and there are no objects remaining in the batch. |
cursor.itcount() | Computes the total number of documents in the cursor client-side by fetching and iterating the result set. |
cursor.limit() | Constrains the size of a cursor's result set. |
cursor.map() | Applies a function to each document in a cursor and collects the return values in an array. |
cursor.max() | Specifies an exclusive upper index bound for a cursor. For use with cursor.hint() |
cursor.maxTimeMS() | Specifies a cumulative time limit in milliseconds for processing operations on a cursor. |
cursor.min() | Specifies an inclusive lower index bound for a cursor. For use with cursor.hint() |
cursor.next() | Returns the next document in a cursor. |
cursor.noCursorTimeout() | Instructs the server to avoid closing a cursor automatically after a period of inactivity. |
cursor.objsLeftInBatch() | Returns the number of documents left in the current cursor batch. |
cursor.readConcern() | Specifies a read concern for adb.collection.find() operation. |
cursor.readPref() | Specifies a read preference to a cursor to control how the client directs queries to a replica set. |
cursor.returnKey() | Modifies the cursor to return index keys rather than the documents. |
cursor.showRecordId() | Adds an internal storage engine ID field to each document returned by the cursor. |
cursor.size() | Returns a count of the documents in the cursor after applyingskip() and limit() methods. |
cursor.skip() | Returns a cursor that begins returning results only after passing or skipping a number of documents. |
cursor.sort() | Returns results ordered according to a sort specification. |
cursor.tailable() | Marks the cursor as tailable. Only valid for cursors over capped collections. |
cursor.toArray() | Returns an array that contains all documents returned by the cursor. |
Note
Limitations
- Automatic 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. |
ClientEncryption.decrypt() | 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. |
ClientEncryption.encrypt() | Encrypts the specified value using the specified encryptionKeyIdand encryptionAlgorithm. |
getClientEncryption() | Returns the ClientEncryption object for the current database collection. |
getKeyVault() | 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. |
KeyVault.createKey() | Adds a data encryption key to the key vault associated to the database connection. |
KeyVault.deleteKey() | Deletes a data encryption key with the specified UUID from the key vault associated to the database connection. |
KeyVault.getKey() | Gets a data encryption key with the specified UUID. The data encryption key must exist in the key vault associated to the database connection. |
KeyVault.getKeyByAltName() | Gets all data encryption keys with the specified keyAltName. |
KeyVault.getKeys() | 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 |
---|---|
rs.add() | Adds a member to the replica set. You must connect to the primary of the replica set to run this method. |
rs.addArb() | Adds an arbiter to an existing replica set. |
rs.config() | Returns a document that contains the current replica set configuration. |
rs.freeze() | 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. |
db.getReplicationInfo() | Returns the status of the replica set from the oplog data. |
rs.initiate() | Initializes a new replica set. |
db.printReplicationInfo() | Returns the oplog of the replica set member that mongosh is connected to. |
rs.printReplicationInfo() | 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 thers.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 thers.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 '} |
rs.reconfig() | Modifies the configuration of an existing replica set. |
rs.remove() | Removes the member specified by hostname from the replica set. |
rs.status() | Returns the status of the replica set member that mongosh is connected to. |
rs.stepDown() | Makes the primary of the replica set a secondary. You must be connected to the primary to run this method. |
rs.syncFrom() | 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.