Navigation

mongo Shell Methods

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 specific methods, including syntax and examples, click on the specific method to go to its reference page.

Collection

Name Description
db.collection.aggregate() Provides access to the aggregation pipeline.
db.collection.bulkWrite() Provides bulk write operation functionality.
db.collection.copyTo() Deprecated. Copies data between collections when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later.
db.collection.count() Wraps count to return a count of the number of documents in a collection or a view.
db.collection.countDocuments() Wraps the $group aggregation stage with a $sum expression to return a count of the number of documents in a collection or a view.
db.collection.estimatedDocumentCount() Wraps count to return an approximate count of the documents in a collection or a view.
db.collection.createIndex() Builds an index on a collection.
db.collection.createIndexes() Builds one or more indexes on a collection.
db.collection.dataSize() Returns the size of the collection. Wraps the size field in the output of the collStats.
db.collection.deleteOne() Deletes a single document in a collection.
db.collection.deleteMany() Deletes multiple documents in a collection.
db.collection.distinct() Returns an array of documents that have distinct values for the specified field.
db.collection.drop() Removes the specified collection from the database.
db.collection.dropIndex() Removes a specified index on a collection.
db.collection.dropIndexes() Removes all indexes on a collection.
db.collection.ensureIndex() Deprecated. Use db.collection.createIndex().
db.collection.explain() Returns information on the query execution of various methods.
db.collection.find() Performs a query on a collection or a view and returns a cursor object.
db.collection.findAndModify() Atomically modifies and returns a single document.
db.collection.findOne() Performs a query and returns a single document.
db.collection.findOneAndDelete() Finds a single document and deletes it.
db.collection.findOneAndReplace() Finds a single document and replaces it.
db.collection.findOneAndUpdate() Finds a single document and updates it.
db.collection.getIndexes() Returns an array of documents that describe the existing indexes on a collection.
db.collection.getShardDistribution() For collections in sharded clusters, db.collection.getShardDistribution() reports data of chunk distribution.
db.collection.getShardVersion() Internal diagnostic method for sharded cluster.
db.collection.hideIndex() Hides an index from the query planner.
db.collection.insert() Creates a new document in a collection.
db.collection.insertOne() Inserts a new document in a collection.
db.collection.insertMany() Inserts several new document in a collection.
db.collection.isCapped() Reports if a collection is a capped collection.
db.collection.latencyStats() Returns latency statistics for a collection.
db.collection.mapReduce() Performs map-reduce style data aggregation.
db.collection.reIndex() Rebuilds all existing indexes on a collection.
db.collection.remove() Deletes documents from a collection.
db.collection.renameCollection() Changes the name of a collection.
db.collection.replaceOne() Replaces a single document in a collection.
db.collection.save() Provides a wrapper around an insert() and update() to insert new documents.
db.collection.stats() Reports on the state of a collection. Provides a wrapper around the collStats.
db.collection.storageSize() Reports the total size used by the collection in bytes. Provides a wrapper around the storageSize field of the collStats output.
db.collection.totalIndexSize() Reports the total size used by the indexes on a collection. Provides a wrapper around the totalIndexSize field of the collStats output.
db.collection.totalSize() Reports the total size of a collection, including the size of all documents and all indexes on a collection.
db.collection.unhideIndex() Unhides an index from the query planner.
db.collection.update() Modifies a document in a collection.
db.collection.updateOne() Modifies a single document in a collection.
db.collection.updateMany() Modifies multiple documents in a collection.
db.collection.watch() Establishes a Change Stream on a collection.
db.collection.validate() Performs diagnostic operations on a collection.

Cursor

Name Description
cursor.addOption() Adds special wire protocol flags that modify the behavior of the query.’
cursor.allowDiskUse() Allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.
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() Controls the number of documents MongoDB will return to the client in a single network message.
cursor.close() Close a cursor and free associated server resources.
cursor.isClosed() Returns true if the cursor is closed.
cursor.collation() Specifies the collation for the cursor returned by the db.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.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.pretty() Configures the cursor to display results in an easy-to-read format.
cursor.readConcern() Specifies a read concern for a 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 applying skip() 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.

Database

Name Description
db.adminCommand() Runs a command against the admin database.
db.aggregate() Runs admin/diagnostic pipeline which does not require an underlying collection.
db.cloneDatabase() Deprecated. Copies a database from a remote host to the current host when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later.
db.commandHelp() Returns help information for a database command.
db.copyDatabase() Deprecated. Copies a database to another database on the current host when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later.
db.createCollection() Creates a new collection or a view. Commonly used to create a capped collection.
db.createView() Creates a view.
db.currentOp() Reports the current in-progress operations.
db.dropDatabase() Removes the current database.
db.eval() Deprecated. Passes a JavaScript function for server-side JavaScript evaluation when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later.
db.fsyncLock() Flushes writes to disk and locks the database to prevent write operations and assist backup operations. Wraps fsync.
db.fsyncUnlock() Allows writes to continue on a database locked with db.fsyncLock().
db.getCollection() Returns a collection or view object. Used to access collections with names that are not valid in the mongo shell.
db.getCollectionInfos() Returns collection information for all collections and views in the current database.
db.getCollectionNames() Lists all collections and views in the current database.
db.getLastError() Checks and returns the status of the last operation. Wraps getLastError.
db.getLastErrorObj() Returns the status document for the last operation. Wraps getLastError.
db.getLogComponents() Returns the log message verbosity levels.
db.getMongo() Returns the Mongo() connection object for the current connection.
db.getName() Returns the name of the current database.
db.getProfilingLevel() Returns the current profiling level for database operations.
db.getProfilingStatus() Returns a document that reflects the current profiling level and the profiling threshold.
db.getReplicationInfo() Returns a document with replication statistics.
db.getSiblingDB() Provides access to the specified database.
db.help() Displays descriptions of common db object methods.
db.hostInfo() Returns a document with information about the system MongoDB runs on. Wraps hostInfo
db.isMaster() Returns a document that reports the state of the replica set.
db.killOp() Terminates a specified operation.
db.listCommands() Displays a list of common database commands.
db.logout() Ends an authenticated session.
db.printCollectionStats() Prints statistics from every collection. Wraps db.collection.stats().
db.printReplicationInfo() Prints a report of the status of the replica set from the perspective of the primary.
db.printShardingStatus() Prints a report of the sharding configuration and the chunk ranges.
db.printSlaveReplicationInfo() Prints a report of the status of the replica set from the perspective of the secondaries.
db.resetError() Deprecated. Resets the last error status.
db.runCommand() Runs a database command.
db.serverBuildInfo() Returns a document that displays the compilation parameters for the mongod instance. Wraps buildinfo.
db.serverCmdLineOpts() Returns a document with information about the runtime used to start the MongoDB instance. Wraps getCmdLineOpts.
db.serverStatus() Returns a document that provides an overview of the state of the database process.
db.setLogLevel() Sets a single log message verbosity level.
db.setProfilingLevel() Modifies the current level of database profiling.
db.shutdownServer() Shuts down the current mongod or mongos process cleanly and safely.
db.stats() Returns a document that reports on the state of the current database.
db.version() Returns the version of the mongod instance.
db.watch() 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
db.collection.getPlanCache() Returns an interface to access the query plan cache object and associated PlanCache methods for a collection.
PlanCache.clear() 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().
PlanCache.clearPlansByQuery() 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()
PlanCache.help() 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().
PlanCache.list()

Returns the plan cache information for a collection. Accessible through the plan cache object of a specific collection, i.e. db.collection.getPlanCache().list().

New in version 4.4.

Bulk Write Operation

Name Description
db.collection.initializeOrderedBulkOp() Initializes a Bulk() operations builder for an ordered list of operations.
db.collection.initializeUnorderedBulkOp() Initializes a Bulk() operations builder for an unordered list of operations.
Bulk() Bulk operations builder.
Bulk.execute() Executes a list of operations in bulk.
Bulk.find() Specifies the query condition for an update or a remove operation.
Bulk.find.arrayFilters() Specifies the filters that determine which elements of an array to update for an update or updateOne operation.
Bulk.find.collation() Specifies the collation for the query condition.
Bulk.find.hint() Specifies the index to use for the update/replace operation.
Bulk.find.remove() Adds a multiple document remove operation to a list of operations.
Bulk.find.removeOne() Adds a single document remove operation to a list of operations.
Bulk.find.replaceOne() Adds a single document replacement operation to a list of operations.
Bulk.find.updateOne() Adds a single document update operation to a list of operations.
Bulk.find.update() Adds a multi update operation to a list of operations.
Bulk.find.upsert() Specifies upsert: true for an update operation.
Bulk.getOperations() Returns an array of write operations executed in the Bulk() operations object.
Bulk.insert() Adds an insert operation to a list of operations.
Bulk.tojson() Returns a JSON document that contains the number of operations and batches in the Bulk() operations object.
Bulk.toString() Returns the Bulk.tojson() results as a string.

User Management

Name Description
db.auth() Authenticates a user to a database.
db.changeUserPassword() Changes an existing user’s password.
db.createUser() Creates a new user.
db.dropUser() Removes a single user.
db.dropAllUsers() Deletes all users associated with a database.
db.getUser() Returns information about the specified user.
db.getUsers() Returns information about all users associated with a database.
db.grantRolesToUser() Grants a role and its privileges to a user.
db.removeUser() Deprecated. Removes a user from a database.
db.revokeRolesFromUser() Removes a role from a user.
db.updateUser() Updates user data.
passwordPrompt() Prompts for the password as an alternative to specifying passwords directly in various mongo shell user authentication/management methods.

Role Management

Name Description
db.createRole() Creates a role and specifies its privileges.
db.dropRole() Deletes a user-defined role.
db.dropAllRoles() Deletes all user-defined roles associated with a database.
db.getRole() Returns information for the specified role.
db.getRoles() Returns information for all the user-defined roles in a database.
db.grantPrivilegesToRole() Assigns privileges to a user-defined role.
db.revokePrivilegesFromRole() Removes the specified privileges from a user-defined role.
db.grantRolesToRole() Specifies roles from which a user-defined role inherits privileges.
db.revokeRolesFromRole() Removes inherited roles from a role.
db.updateRole() Updates a user-defined role.

Replication

Name Description
rs.add() Adds a member to a replica set.
rs.addArb() Adds an arbiter to a replica set.
rs.conf() Returns the replica set configuration document.
rs.freeze() Prevents the current member from seeking election as primary for a period of time.
rs.help() Returns basic help text for replica set functions.
rs.initiate() Initializes a new replica set.
rs.printReplicationInfo() Prints a report of the status of the replica set from the perspective of the primary.
rs.printSlaveReplicationInfo() Prints a report of the status of the replica set from the perspective of the secondaries.
rs.reconfig() Re-configures a replica set by applying a new replica set configuration object.
rs.remove() Remove a member from a replica set.
rs.status() Returns a document with information about the state of the replica set.
rs.stepDown() Causes the current primary to become a secondary which forces an election.
rs.syncFrom() Sets the member that this replica set member will sync from, overriding the default sync target selection logic.

Sharding

Name Description
sh.addShard() Adds a shard to a sharded cluster.
sh.addShardTag() In MongoDB 3.4, this method aliases to sh.addShardToZone().
sh.addShardToZone() Associates a shard to a zone. Supports configuring zones in sharded clusters.
sh.addTagRange() In MongoDB 3.4, this method aliases to sh.updateZoneKeyRange().
sh.balancerCollectionStatus()

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

New in version 4.4.

sh.disableBalancing() Disable balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.
sh.enableBalancing() Activates the sharded collection balancer process if previously disabled using sh.disableBalancing().
sh.disableAutoSplit() Disables auto-splitting for the sharded cluster.
sh.enableAutoSplit() Enables auto-splitting for the sharded cluster.
sh.enableSharding() Enables sharding on a specific database.
sh.getBalancerHost() Deprecated since MongoDB 3.4
sh.getBalancerState() Returns a boolean to report if the balancer is currently enabled.
sh.removeTagRange() In MongoDB 3.4, this method aliases to sh.removeRangeFromZone().
sh.removeRangeFromZone() Removes an association between a range of shard keys and a zone. Supports configuring zones in sharded clusters.
sh.help() Returns help text for the sh methods.
sh.isBalancerRunning() Returns a boolean to report if the balancer process is currently migrating chunks.
sh.moveChunk() Migrates a chunk in a sharded cluster.
sh.removeShardTag() In MongoDB 3.4, this method aliases to sh.removeShardFromZone().
sh.removeShardFromZone() Removes the association between a shard and a zone. Use to manage zone sharding.
sh.setBalancerState() Enables or disables the balancer which migrates chunks between shards.
sh.shardCollection() Enables sharding for a collection.
sh.splitAt() Divides an existing chunk into two chunks using a specific value of the shard key as the dividing point.
sh.splitFind() Divides an existing chunk that contains a document matching a query into two approximately equal chunks.
sh.startBalancer() Enables the balancer and waits for balancing to start.
sh.status() Reports on the status of a sharded cluster, as db.printShardingStatus().
sh.stopBalancer() Disables the balancer and waits for any in progress balancing rounds to complete.
sh.waitForBalancer() Internal. Waits for the balancer state to change.
sh.waitForBalancerOff() Internal. Waits until the balancer stops running.
sh.waitForPingChange() Internal. Waits for a change in ping state from one of the mongos in the sharded cluster.
sh.updateZoneKeyRange() Associates a range of shard keys to a zone. Supports configuring zones in sharded clusters.
convertShardKeyToHashed() Returns the hashed value for the input.

Free Monitoring

Name Description
db.enableFreeMonitoring() Enables free monitoring during runtime.
db.disableFreeMonitoring() Disables free monitoring during runtime.
db.getFreeMonitoringStatus() Returns the free monitoring status.

Constructors

Name Description
BulkWriteResult() Wrapper around the result set from Bulk.execute().
Date() Creates a date object. By default creates a date object including the current date.
ObjectId() Returns an ObjectId.
ObjectId.getTimestamp() Returns the timestamp portion of an ObjectId.
ObjectId.toString() Displays the string representation of an ObjectId.
ObjectId.valueOf() Displays the str attribute of an ObjectId as a hexadecimal string.
UUID() Converts a 32-byte hexadecimal string to the UUID BSON subtype.
WriteResult() Wrapper around the result set from write methods.
WriteResult.hasWriteError() Returns a boolean specifying whether the results include WriteResult.writeError.
WriteResult.hasWriteConcernError() Returns a boolean specifying whether whether the results include WriteResult.writeConcernError.

Connection

Name Description
connect() Connects to a MongoDB instance and to a specified database on that instance.
Mongo() Creates a new connection object.
Mongo.getDB() Returns a database object.
Mongo.getReadPrefMode() Returns the current read preference mode for the MongoDB connection.
Mongo.getReadPrefTagSet() Returns the read preference tag set for the MongoDB connection.
Mongo.isCausalConsistency() Indicates whether causal consistency is enabled on the connection object.
Mongo.setCausalConsistency() Enables or disables causal consistency on the connection object.
Mongo.setReadPref() Sets the read preference for the MongoDB connection.
Mongo.startSession() Starts a session on the connection object.
Mongo.watch() 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.
Session The session object.
SessionOptions The options object for the session.

Native

Name Description
cat() Returns the contents of the specified file.
cd() Changes the current working directory to the specified path.
copyDbpath() Copies a local dbPath. For internal use.
getHostName() Returns the hostname of the system running the mongo shell.
getMemInfo() Returns a document that reports the amount of memory used by the shell.
hostname() Returns the hostname of the system running the shell.
isInteractive() Returns a boolean indicating whether the mongo shell is running in interactive or script mode.
listFiles() Returns an array of documents that give the name and size of each object in the directory.
load() Loads and runs a JavaScript file in the shell.
ls() Returns a list of the files in the current directory.
md5sumFile() The md5 hash of the specified file.
mkdir() Creates a directory at the specified path.
pwd() Returns the current directory.
quit() Exits the current shell session.
removeFile() Removes the specified file from the local file system.
resetDbpath() Removes a local dbPath. For internal use.
sleep() Suspends the mongo shell for a given period of time.
setVerboseShell() Configures the mongo shell to report operation timing.
version() Returns the current version of the mongo shell instance.
_isWindows() Returns true if the shell runs on a Windows system; false if a Unix or Linux system.
_rand() Returns a random number between 0 and 1.

Client-Side Field Level Encryption

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:

  • Use the Mongo() constructor from the mongo shell to establish a connection with the required client-side field level encryption options. The Mongo() method supports both Amazon Web Services and Local Key Management Service (KMS) providers for Customer Master Key (CMK) management.

    or

  • Use the mongo shell command line options to establish a connection with the required options. The command line options only support the AWS KMS provider for CMK management.

Name Description
getKeyVault() Returns the key vault object for the current MongoDB connection.
KeyVault.createKey() Creates a data encryption key for use with client-side field level encryption.
KeyVault.deleteKey() Deletes the specified data encryption key from the key vault.
KeyVault.getKey() Retreives the specified data encryption key from the key vault.
KeyVault.getKeys() Retrieves all keys in the key vault.
KeyVault.addKeyAlternateName() Associates a key alternative name to the specified data encryption key.
KeyVault.removeKeyAlternateName() Removes a key alternative name from the specified data encryption key.
KeyVault.getKeyByAltName() Retrieves keys with the specified key alternative name.
getClientEncryption() Returns the client encryption object for supporting explicit encryption/decryption of fields.
ClientEncryption.encrypt() Encrypts a field using a specified data encryption key and encryption algorithm.
ClientEncryption.decrypt() Decrypts a field using the associated data encryption key and encryption algorithm.