Methods
On this page
- Administration Methods
- Atlas Search Index Methods
- Bulk Operation Methods
- Collection Methods
- Connection Methods
- Cursor Methods
- Database Methods
- Client-Side Field Level Encryption Methods
- Native Methods
- Query Plan Cache Methods
- Replication Methods
- Role Management Methods
- Session Object Methods
- Server Status Methods
- Sharding Methods
- Telemetry Methods
- Transaction Methods
- User Management Methods
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
Administration Methods
Method | Description |
---|---|
Runs a command against the admin database. | |
Reports the current in-progress operations. | |
Terminates a specified operation. | |
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() . |
Atlas Search Index Methods
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 on MongoDB Atlas.
Name | Description |
---|---|
Creates one or more Atlas Search indexes on a specified
collection. | |
Deletes an existing Atlas Search index. | |
Returns information about existing Atlas Search indexes on a specified
collection. | |
Updates an existing Atlas Search index. |
Bulk Operation Methods
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. |
Collection Methods
Method | Description |
---|---|
Provides access to the
aggregation pipeline. | |
Provides bulk write operation functionality. | |
Deprecated in mongosh 1.0.6. Use
db.collection.countDocuments() or
db.collection.estimatedDocumentCount() instead. | |
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. | |
Deprecated. Use | |
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. | |
Returns information regarding the state of data in a sharded
cluster. | |
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. |
Connection Methods
Method | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
JavaScript constructor to instantiate a database connection from
the The
| ||||||||||
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. |
Cursor Methods
Method | Description | |
---|---|---|
Adds special wire protocol flags that modify the behavior of the
query. | ||
Allows | ||
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:
| ||
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 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. |
Database Methods
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. | |
Returns the current database connection. | |
Returns the current log verbosity settings. | |
Returns the name of the current database. | |
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. | |
Runs a database command. | |
Sets a single verbosity level for log messages. | |
Opens a change stream cursor for a
database to report on all its non-system collections. |
Client-Side Field Level Encryption Methods
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 |
---|---|
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. | |
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. |
Native Methods
Method | Description | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Returns the following JSON-formatted document that describes
your
| |||||||||||||||||||
| Changes the current working directory to the specified path. | |||||||||||||||||||
| Returns a boolean indicating whether mongosh is running in
interactive or script mode. | |||||||||||||||||||
| Loads and runs a JavaScript file in the shell. In The legacy | |||||||||||||||||||
| Print the specified text or variable.
| |||||||||||||||||||
| Returns the current working directory of the active shell session. | |||||||||||||||||||
| Exits the current shell session. | |||||||||||||||||||
| Suspends the mongo shell for a given period of time. | |||||||||||||||||||
| Returns the current version of the mongosh instance. |
Query Plan Cache Methods
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. |
Replication Methods
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 The following is an example output from the
| |||||||||||
rs.printSecondaryReplicationInfo | Returns the status of the secondary members of the replica set. This is identical to the The following is an example output from the
| |||||||||||
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. |
Role Management Methods
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. |
Session Object Methods
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() . |
Server Status Methods
Method | Description |
---|---|
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. |
Sharding Methods
Method | Description |
---|---|
Adds a shard to a sharded cluster. | |
Aliases to sh.addShardToZone() . | |
Associates a shard with a zone. Supports configuring zones in sharded
clusters. | |
Aliases to sh.updateZoneKeyRange() . | |
Returns information on whether the chunks of a sharded collection are balanced. New in version 4.4. | |
Disables automatic chunk merges for a namespace. New in version 7.0. | |
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 automatic chunk merges for a namespace. New in version 7.0. | |
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 data distribution information for sharded collections.
sh.getShardedDataDistribution() is a shell helper method for
the $shardedDataDistribution aggregation pipeline
stage. | |
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 sharding for a collection. | |
Divides an existing chunk that contains a document
matching a query into two approximately equal chunks. | |
Enables the AutoMerger. New in version 7.0. | |
Enables the balancer. | |
Reports on the status of a sharded cluster. | |
Disables the AutoMerger. New in version 7.0. | |
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. |
Telemetry Methods
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.
Method | Description |
---|---|
Disable telemetry for mongosh . | |
Enable telemetry for mongosh . |
Transaction Methods
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. |
User Management Methods
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. |