Docs Menu
Docs Home
/
MongoDB Manual
/

mongosh Methods

On this page

  • Collection
  • Cursor
  • Database
  • Query Plan Cache
  • Bulk Write Operation
  • User Management
  • Role Management
  • Replication
  • Sharding
  • Constructors
  • Connection
  • Native
  • Client-Side Field Level Encryption

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.

Name
Description
db.collection.aggregate()
Provides access to the aggregation pipeline.
Provides bulk write operation functionality.
Wraps count to return a count of the number of documents in a collection or a view.
Wraps the $group aggregation stage with a $sum expression 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.
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.
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 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.
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.
Removed in MongoDB 5.0. Resets the last error status.
Performs online TLS certificate rotation. Wraps rotateCertificates.
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.
Shuts down the current mongod or mongos process cleanly and safely.
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.
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. db.collection.getPlanCache().list().
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.
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.
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.
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.
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.
Causes the current primary to become a secondary which forces an election.
Sets the member that this replica set member will sync from, overriding the default sync target selection logic.
Name
Description

Aborts a resharding operation.

New in version 5.0.

Adds a shard to a sharded cluster.
This method aliases to sh.addShardToZone().
Associates a shard to a zone. Supports configuring zones in sharded clusters.
This method aliases to sh.updateZoneKeyRange().
Returns information on whether the chunks of a sharded collection are balanced.

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.
Enables auto-splitting for the sharded cluster.
Enables sharding on a specific database.
Returns a boolean to report if the balancer is currently enabled.
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 boolean to report if the balancer process is currently migrating chunks.
Migrates a chunk in a sharded cluster.
This method is an alias for 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 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 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.
Name
Description
Returns a binary data object.
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.
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.
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.
Name
Description
Returns the contents of the specified file.
Changes the current working directory to the specified path.
Copies a local dbPath. For internal use.
Returns the hostname of the system running mongosh.
Returns a document that reports the amount of memory used by the shell.
Returns the hostname of the system running the shell.
Returns a boolean indicating whether mongosh is running in interactive or script mode.
Returns an array of documents that give the name and size of each object in the directory.
Loads and runs a JavaScript file in the shell.
Returns a list of the files in the current directory.
The md5 hash of the specified file.
Creates a directory at the specified path.
Returns the current directory.
Exits the current shell session.
Removes the specified file from the local file system.
Removes a local dbPath. For internal use.
Suspends mongosh for a given period of time.
Configures mongosh to report operation timing.
Returns the current version of mongosh instance.
Returns true if the shell runs on a Windows system; false if a Unix or Linux system.
Returns a random number between 0 and 1.

Note

The mongo 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:

Name
Description
Returns the key vault object for the current MongoDB connection.
Creates a data encryption key for use with client-side field level encryption.
Deletes the specified data encryption key from the key vault.
Retreives the specified data encryption key from the key vault.
Retrieves all keys in the key vault.
Associates a key alternative name to the specified data encryption key.
Removes a key alternative name from the specified data encryption key.
Retrieves keys with the specified key alternative name.
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.

Back

Wire Protocol