mongosh
Methods
On this page
Note
JavaScript in MongoDB
Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.
Note
For details on a specific method, including syntax and examples, click on the link to the method's reference page.
Collection
Name | Description |
---|---|
Provides access to the aggregation pipeline. | |
Provides bulk write operation functionality. | |
Wraps compactStructuredEncryptionData to return
a success or failure object. | |
Wraps count to return a count of the number of 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. | |
Removed. Use db.collection.createIndex() . | |
Wraps count to return an approximate count of the documents in a collection or a view. | |
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. | |
For collections in sharded clusters, db.collection.getShardDistribution() reports data of chunk distribution. | |
Internal diagnostic method for sharded cluster. | |
Hides an index from the query planner. | |
Inserts a new document into a collection. | |
Inserts several new documents into a collection. | |
Reports if a collection is a capped collection. | |
Returns latency statistics for a collection. | |
Performs map-reduce style data aggregation. | |
Rebuilds all existing indexes on a collection. | |
Deletes documents from 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. | |
Unhides an index from the query planner. | |
Modifies a single document in a collection. | |
Modifies multiple documents in a collection. | |
Establishes a Change Stream on a collection. | |
Performs diagnostic operations on a collection. |
Cursor
Name | Description |
---|---|
Adds special wire protocol flags that modify the behavior of the query.' | |
Allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation. | |
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. | |
Controls the number of documents MongoDB will return to the client in a single network message. | |
Close a cursor and free associated server resources. | |
Returns true if the cursor is closed. | |
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 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. | |
Configures the cursor to display results in an easy-to-read format. | |
Specifies a read concern for a 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
Name | Description |
---|---|
Runs a command against the admin database. | |
Runs admin/diagnostic pipeline which does not require an underlying collection. | |
Returns help information for a database command. | |
Creates a new collection or a view. Commonly used to create a capped collection. | |
Creates a view. | |
Reports the current in-progress operations. | |
Removes the current database. | |
Flushes writes to disk and locks the database to prevent write operations and assist backup operations. Wraps fsync . | |
Allows writes to continue on a database locked with db.fsyncLock() . | |
Returns a collection or view object. Used to access collections with names that are not valid in mongosh . | |
Returns collection information for all collections and views in the current database. | |
Lists all collections and views in the current database. | |
Returns the log message verbosity levels. | |
Returns the Mongo() connection object for the current connection. | |
Returns the name of the current database. | |
Returns a document that reflects the current profiling level and the profiling threshold. | |
Returns a document with replication statistics. | |
Provides access to the specified database. | |
Returns a document that reports the state of the replica set. | |
Displays descriptions of common db object methods. | |
Returns a document with information about the system MongoDB runs on. Wraps hostInfo | |
Terminates a specified operation. | |
Displays a list of common database commands. | |
Deprecated. Ends an authenticated session. | |
Prints statistics from every collection. Wraps db.collection.stats() . | |
Prints a report of the status of the replica set from the perspective of the primary. | |
Prints the status of the replica set from the
perspective of the secondaries. | |
Prints a report of the sharding configuration and the chunk ranges. | |
Deprecated since version 4.4.1: Use
| |
Removed in MongoDB 5.0. Resets the last error status. | |
Performs online TLS certificate rotation. Wraps
rotateCertificates . | |
Runs a database command. | |
Returns a document that displays the compilation parameters for the mongod instance. Wraps buildInfo . | |
Returns a document with information about the runtime used to start the MongoDB instance. Wraps getCmdLineOpts . | |
Returns a document that provides an overview of the state of the database process. | |
Sets a single log message verbosity level. | |
Modifies the current level of database profiling. | |
Returns a document that reports on the state of the current database. | |
Returns the version of the mongod instance. | |
Opens a change stream cursor for a database
to report on all its non- system collections. Cannot be opened on
the admin , local or config databases. |
Query Plan Cache
Name | Description |
---|---|
Returns an interface to access the query plan cache object and
associated PlanCache methods for a collection. | |
Clears all the cached query plans for a collection.
Accessible through the plan cache object of a specific collection,
i.e. db.collection.getPlanCache().clear() . | |
Clears the cached query plans for the specified query shape.
Accessible through the plan cache object of a specific collection,
i.e. db.collection.getPlanCache().clearPlansByQuery() | |
Displays the methods available for a collection's query plan cache.
Accessible through the plan cache object of a specific collection,
i.e. db.collection.getPlanCache().help() . | |
Returns the plan cache information for a collection. Accessible
through the plan cache object of a specific collection, i.e.
New in version 4.4. |
Bulk Write Operation
Name | Description |
---|---|
Initializes a Bulk() operations builder for an ordered list of operations. | |
Initializes a Bulk() operations builder for an unordered list of operations. | |
Bulk operations builder. | |
Executes a list of operations in bulk. | |
Specifies the query condition for an update or a remove operation. | |
Specifies the filters that determine which elements of an array to update for an update or updateOne operation. | |
Specifies the collation for the query condition. | |
Adds a multiple document delete operation to a list of operations. | |
Adds a single document delete operation to a list of operations. | |
Specifies the index to use for the update/replace operation. | |
An alias for Bulk.find.delete() . | |
An alias for Bulk.find.deleteOne() . | |
Adds a single document replacement operation to a list of operations. | |
Adds a single document update operation to a list of operations. | |
Adds a multi update operation to a list of operations. | |
Specifies upsert: true for an update operation. | |
Returns an array of write operations executed in the Bulk() operations object. | |
Adds an insert operation to a list of operations. | |
Returns a JSON document that contains the number of operations and batches in the Bulk() operations object. | |
Returns the Bulk.toJSON() results as a string. |
User Management
Name | Description |
---|---|
Authenticates a user to a database. | |
Changes an existing user's password. | |
Creates a new user. | |
Removes a single user. | |
Deletes all users associated with a database. | |
Returns information about the specified user. | |
Returns information about all users associated with a database. | |
Grants a role and its privileges to a user. | |
Deprecated. Removes a user from a database. | |
Removes a role from a user. | |
Updates user data. | |
Prompts for the password as an alternative to specifying passwords
directly in various mongosh user
authentication/management methods. |
Role Management
Name | 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. |
Replication
Name | Description |
---|---|
Adds a member to a replica set. | |
Adds an arbiter to a replica set. | |
Returns the replica set configuration document. | |
Prevents the current member from seeking election as primary for a period of time. | |
Returns basic help text for replica set functions. | |
Initializes a new replica set. | |
Prints a formatted report of the replica set status from the
perspective of the primary. | |
Prints a formatted report of the replica set status from the
perspective of the secondaries. | |
Deprecated since version 4.4.1: Use
| |
Re-configures a replica set by applying a new replica set configuration object. | |
Remove a member from a replica set. | |
Returns a document with information about the state of the replica set. | |
Sets the member that this replica set member will sync from, overriding the default sync target selection logic. |
Sharding
Name | Description |
---|---|
Aborts a resharding operation. New in version 5.0. | |
Adds a shard to a sharded cluster. | |
In MongoDB 3.4, this method aliases to sh.addShardToZone() . | |
Associates a shard to a zone. Supports configuring zones in sharded clusters. | |
In MongoDB 3.4, this method aliases to sh.updateZoneKeyRange() . | |
Returns information on whether the chunks of a sharded collection are balanced. New in version 4.4. | |
Forces a resharding operation to block writes and complete. New in version 5.0. | |
Disable balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster. | |
Activates the sharded collection balancer process if previously disabled using sh.disableBalancing() . | |
Disables auto-splitting for the sharded cluster. Starting in MongoDB 6.1, automatic chunk splitting is not performed. This is because of balancing policy improvements. Auto-splitting commands still exist, but do not perform an operation. For details, see Balancing Policy Changes. | |
Enables auto-splitting for the sharded cluster. Starting in MongoDB 6.1, automatic chunk splitting is not performed. This is because of balancing policy improvements. Auto-splitting commands still exist, but do not perform an operation. For details, see Balancing Policy Changes. | |
Creates a database. | |
Returns a boolean to report if the balancer is currently enabled. | |
In MongoDB 3.4, this method aliases to sh.removeRangeFromZone() . | |
Removes an association between a range of shard keys and a zone. Supports configuring zones in sharded clusters. | |
Returns help text for the sh methods. | |
Returns a document describing the status of the balancer. | |
Migrates a chunk in a sharded cluster. | |
In MongoDB 3.4, this method aliases to sh.removeShardFromZone() . | |
Removes the association between a shard and a zone. Use to manage zone sharding. | |
Initiates a resharding operation to change the shard key for a collection, changing the distribution of your data. New in version 5.0. | |
Enables sharding for a collection. | |
Divides an existing chunk that contains a document matching a query into two approximately equal chunks. | |
Enables the balancer and waits for balancing to start. | |
Reports on the status of a sharded cluster, as db.printShardingStatus() . | |
Disables the balancer and waits for any in progress balancing rounds to complete. | |
Internal. Waits for the balancer state to change. | |
Internal. Waits until the balancer stops running. | |
Internal. Waits for a change in ping state from one of the mongos in the sharded cluster. | |
Associates a range of shard keys to a zone. Supports configuring zones in sharded clusters. | |
Returns the hashed value for the input. |
Free Monitoring
Name | Description |
---|---|
Enables free monitoring during runtime. | |
Disables free monitoring during runtime. | |
Returns the free monitoring status. |
Constructors
Name | Description |
---|---|
Wrapper around the result set from Bulk.execute() . | |
Creates a date object. By default creates a date object including the current date. | |
Returns an ObjectId. | |
Returns the timestamp portion of an ObjectId. | |
Displays the string representation of an ObjectId. | |
Displays the str attribute of an ObjectId as a hexadecimal string. | |
Converts a 32-byte hexadecimal string to the UUID BSON subtype. | |
Wrapper around the result set from write methods. | |
Returns a boolean specifying whether the results include WriteResult.writeError . | |
Returns a boolean specifying whether whether the results include WriteResult.writeConcernError . |
Connection
Name | Description |
---|---|
Connects to a MongoDB instance and to a specified database on that instance. | |
Creates a new connection object. | |
Returns a database object. | |
Returns the current read preference mode for the MongoDB connection. | |
Returns the read preference tag set for the MongoDB connection. | |
Enables or disables causal consistency on the connection object. | |
Sets the read preference for the MongoDB connection. | |
Starts a session on the connection object. | |
Opens a change stream cursor for a deployment
to report on all its non- system collections across all its
databases, excluding the internal admin , local , and
config databases. | |
The session object. | |
The options object for the session. |
Client-Side Field Level Encryption
Note
The mongosh
client-side field level encryption methods
require a database connection with client-side field level encryption
enabled. If the current database connection was not initiated with
client-side field level encryption enabled, either:
Use the
Mongo()
constructor from themongosh
to establish a connection with the required client-side field level encryption options. TheMongo()
method supports the following Key Management Service (KMS) providers for Customer Master Key (CMK) management:or
Use the
mongosh
command line options to establish a connection with the required options. The command line options only support the Amazon Web Services KMS provider for CMK management.
Name | Description |
---|---|
Returns the key vault object for the current MongoDB connection. | |
An alias for KeyVault.createKey() . | |
Creates a data encryption key for use with client-side field level encryption. | |
Deletes the specified data encryption key from the key vault. | |
Retrieves the specified data encryption key from the key vault. | |
Retrieves all keys in the key vault. | |
Associates a key's alternative name to the specified data encryption key. | |
An alias for KeyVault.addKeyAlternateName() . | |
Removes a key's alternative name from the specified data encryption key. | |
An alias for KeyVault.removeKeyAlternateName() . | |
Retrieves keys with the specified key alternative name. | |
Decrypts multiple data keys and re-encrypts them. | |
Returns the client encryption object for supporting explicit encryption/decryption of fields. | |
Encrypts a field using a specified data encryption key and encryption algorithm. | |
Decrypts a field using the associated data encryption key and encryption algorithm. |