Navigation

mongosh Methods

On this page

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.

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
Method
Description
Runs a command against the admin database.
Reports the current in-progress operations.
Terminates a specified operation.
Shuts down the current mongod or mongos process cleanly and safely.
Flushes writes to disk and locks the database to prevent write operations and assist backup operations.
Allows writes to continue on a database locked with db.fsyncLock().
Method
Description
Initializes and returns a new Bulk() operations builder for a collection. The builder constructs an ordered list of write operations that MongoDB executes in bulk.
Initializes and returns a new Bulk() operations builder for a collection. The builder constructs an unordered list of write operations that MongoDB executes in bulk.
Creates a bulk operations builder used to construct a list of write operations to perform in bulk for a single collection. To instantiate the builder, use either the db.collection.initializeOrderedBulkOp() or the db.collection.initializeUnorderedBulkOp() method.
Executes the list of operations built by the Bulk() operations builder.
Specifies a query condition for an update or a remove operation.
Sets the hint option that specifies the index to support the bulk operation.
Adds a remove operation to a bulk operations list.
Adds a single document remove operation to a bulk operations list.
Adds a single document replacement operation to a bulk operations list.
Adds a single document update operation to a bulk operations list.
Adds a multi update operation to a bulk operations list. The method updates specific fields in existing documents.
Sets the upsert option to true for an update or a replacement operation.
Returns an array of write operations executed through Bulk.execute().
Adds an insert operation to a bulk operations list.
Returns a JSON document that contains the number of operations and batches in the Bulk() object.
Returns as a string a JSON document that contains the number of operations and batches in the Bulk() object.
Method
Description
Provides access to the aggregation pipeline.

Provides bulk write operation functionality.

Returns a count of the number of documents in a collection or a view.
Returns a count of the number of documents in a collection or a view. Wraps the $group aggregation stage with a $sum expression.
Returns an approximate count of the documents in a collection or a view.
Builds an index on a collection.
Builds one or more indexes on a collection.
Returns the size of the collection. Wraps the size field in the output of the collStats.
Deletes a single document in a collection.
Deletes multiple documents in a collection.
Returns an array of documents that have distinct values for the specified field.
Removes the specified collection from the database.
Removes a specified index on a collection.
Removes all indexes on a collection.
Returns information on the query execution of various methods.
Performs a query on a collection or a view and returns a cursor object.
Atomically modifies and returns a single document.
Performs a query and returns a single document.
Finds a single document and deletes it.
Finds a single document and replaces it.
Finds a single document and updates it.

Returns an array of documents that describe the existing indexes on a collection.

Prints the data distribution statistics for a sharded collection.
Provides a wrapper for the database command getShardVersion.
Inserts a new document in a collection.
Inserts several new document in a collection.
Reports if a collection is a capped collection.
Runs map-reduce aggregation operations on a collection.
Rebuilds all existing indexes on a collection.
Changes the name of a collection.
Replaces a single document in a collection.
Reports on the state of a collection. Provides a wrapper around the collStats.
Reports the total size used by the collection in bytes. Provides a wrapper around the storageSize field of the collStats output.
Reports the total size used by the indexes on a collection. Provides a wrapper around the totalIndexSize field of the collStats output.
Reports the total size of a collection, including the size of all documents and all indexes on a collection.
Modifies a single document in a collection.
Modifies multiple documents in a collection.
Validates a collection.
Opens a change stream cursor on the collection.
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.

ClientSideFieldLevelEncryptionOptions
Document

Optional

New in version 4.2.

Configuration parameters for enabling Client-Side Field Level Encryption.

ClientSideFieldLevelEncryptionOptions 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 ClientSideFieldLevelEncryptionOptions.

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.

cursor.batchSize()

Controls the number of documents MongoDB will return to the client in a single network message.

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 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.
Method
Description
Runs admin/diagnostic pipeline which does not require an underlying collection.
Creates a new collection or view.
Creates a view as the result of applying the specified aggregation pipeline to the source collection or view.
Displays help text for the specified database command.
Removes the current database.
Returns a collection or view object. Used to access collections with names that are not valid in the mongo shell.
Returns collection information for all collections and views in the current database.
Lists all collections and views in the current database.
Checks and returns the status of the last operation. Wraps getLastError.
Returns the status document for the last operation. Wraps getLastError.
Returns the current database connection.
Returns the current log verbosity settings.
Returns the name of the current database.
Returns the current profile level, slowOpThresholdMs setting, and slowOpSampleRate setting.
Provides access to the specified database.
Provides a list of all database commands.
Ends an authenticated session.
Prints a formatted report of the sharding configuration and the information regarding existing chunks in a sharded cluster.
Sets a single verbosity level for log messages.
Configures the database profiler level, slowms, and sampleRate.
Opens a change stream cursor for a database to report on all its non-system collections.

Starting in MongoDB 4.0, MongoDB (Community Edition) offers free cloud monitoring for standalone and replica set deployments.

Note

Free cloud monitoring is only available for MongoDB Community Edition.

Method
Description
Disables free cloud monitoring for your deployment.
Enables free cloud monitoring for your deployment.
Returns the free cloud monitoring status for your deployment.
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
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.
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.
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

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.

In the legacy shell, you cannot not access the script's file name or directory using 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
sleep()
Suspends the mongo shell for a given period of time.
version()
Returns the current version of the mongosh instance.
Method
Description
Returns an interface to access the query plan cache object and associated PlanCache methods for a collection.
Removes all cached query plans for a collection.
Clears the cached query plans for the specified query shape.
Lists the methods available to view and modify a collection’s query plan cache.
Returns an array of plan cache entries for a collection.
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. This method's output is similar to the db.printSlaveReplicationInfo() method. The db.printSlaveReplicationInfo() method is deprecated in mongosh. Use db.printSecondaryReplicationInfo() instead.

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. This method's output is similar to the rs.printSlaveReplicationInfo() method in the legacy mongo shell. The rs.printSlaveReplicationInfo() method is deprecated in mongosh. Use rs.printSecondaryReplicationInfo() instead.

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.
Method
Description
Creates a role and specifies its privileges.
Deletes a user-defined role.
Deletes all user-defined roles associated with a database.
Returns information for the specified role.
Returns information for all the user-defined roles in a database.
Assigns privileges to a user-defined role.
Removes the specified privileges from a user-defined role.
Specifies roles from which a user-defined role inherits privileges.
Removes inherited roles from a role.
Updates a user-defined role.
Method
Description
Starts a session for the connection.
Updates the operation time.
Ends the session.
Returns the most recent cluster time as seen by the session.
Access the specified database from the session in the shell.
Returns the timestamp of the last acknowledged operation for the session.
Returns the options for the session.
Returns a boolean that specifies whether the session has ended.
The options for a session in the shell. To access the SessionOptions() object, use Session.getOptions().
Method
Description

Returns a document that describes the role of the mongod instance.

If the mongod is a member of a replica set, then the isWritablePrimary and secondary fields report if the instance is the primary or if it is a secondary member of the replica set.

Returns a document with information about the system running the MongoDB instance.
Returns latency statistics for a specified collection.
Returns statistics from every collection.
Returns a document that displays the compilation parameters for the mongod instance.
Returns a document with information about the runtime options used to start the MongoDB instance.
Returns a document that provides an overview of the database process.
Returns a document that reports on the state of the current database.
Returns the version of the mongod instance.
Method
Description
Adds a shard to a sharded cluster.
Associates a shard with a zone. Supports configuring zones in sharded clusters.

Returns information on whether the chunks of a sharded collection are balanced.

New in version 4.4.

Disables auto-splitting for the sharded cluster.
Disables balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.
Enables auto-splitting for the sharded cluster.
Activates the sharded collection balancer process if previously disabled using sh.disableBalancing().
Enables sharding on a specific database.
Returns a boolean to report if the balancer is currently enabled.
Returns a boolean to report if the balancer process is currently migrating chunks.
Migrates a chunk in a sharded cluster.
Removes the association between a range of shard key values and a zone.
Removes the association between a shard and a zone.
Removes the association between a tag and a shard.
Removes a range of shard key values to a shard tag created using the sh.addShardTag() method. This method aliases to sh.removeRangeFromZone() in MongoDB 3.4.
Enables or disables the balancer which migrates chunks between shards.
Enables sharding for a collection.
Divides an existing chunk into two chunks using a specific value of the shard key as the dividing point.
Divides an existing chunk that contains a document matching a query into two approximately equal chunks.
Enables the balancer.
Reports on the status of a sharded cluster.
Disables the balancer. This operation does not wait for the balancer to complete any in progress operations, and may terminate ongoing operations.
Associates a range of shard keys with a zone. Supports configuring zones in sharded clusters.
Method
Description
Terminates a multi-document transaction and rolls back any data changes made by the operations within the transaction.
Saves the changes made by the operations in a multi-document transaction and ends the transaction.
Starts a multi-document transaction associated with the session.
Important

The passwordPrompt() method is currently not supported in mongosh. As a result, when using the following methods you must specify the password as a parameter:

Method
Description
Authenticates a user to a database.
Changes an existing user’s password.
Creates a new user.
Deletes all users associated with a database.
Deletes a single user.
Returns information about the specified user.
Returns information about all users associated with a database.
Updates a specified user's data.
Grants a role and its privileges to a user.
Removes a role from a user.
Give Feedback

On this page