Navigation

mongosh Methods

Info With Circle IconCreated with Sketch.Note
Beta

The MongoDB Shell (mongosh) is currently available as a Beta release. The product, its features, and the corresponding documentation may change during the Beta stage.

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 With Circle IconCreated with Sketch.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
MethodDescription
db.adminCommandRuns a command against the admin database.
db.currentOpReports the current in-progress operations.
db.killOpTerminates a specified operation.
db.shutdownServerShuts down the current mongod or mongos process cleanly and safely.
db.fsyncLockFlushes writes to disk and locks the database to prevent write operations and assist backup operations.
db.fsyncUnlockAllows writes to continue on a database locked with db.fsyncLock.
MethodDescription
db.collection.initializeOrderedBulkOpInitializes and returns a new Bulk operations builder for a collection. The builder constructs an ordered list of write operations that MongoDB executes in bulk.
db.collection.initializeUnorderedBulkOpInitializes and returns a new Bulk operations builder for a collection. The builder constructs an unordered list of write operations that MongoDB executes in bulk.
BulkCreates 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.
Bulk.executeExecutes the list of operations built by the Bulk operations builder.
Bulk.findSpecifies a query condition for an update or a remove operation.
Bulk.find.hintSets the hint option that specifies the index to support the bulk operation.
Bulk.find.removeAdds a remove operation to a bulk operations list.
Bulk.find.removeOneAdds a single document remove operation to a bulk operations list.
Bulk.find.replaceOneAdds a single document replacement operation to a bulk operations list.
Bulk.find.updateOneAdds a single document update operation to a bulk operations list.
Bulk.find.updateAdds a multi update operation to a bulk operations list. The method updates specific fields in existing documents.
Bulk.find.upsertSets the upsert option to true for an update or a replacement operation.
Bulk.getOperationsReturns an array of write operations executed through Bulk.execute.
Bulk.insertAdds an insert operation to a bulk operations list.
Bulk.tojsonReturns a JSON document that contains the number of operations and batches in the Bulk object.
Bulk.toStringReturns as a string a JSON document that contains the number of operations and batches in the Bulk object.
MethodDescription
db.collection.aggregateProvides access to the aggregation pipeline.
db.collection.bulkWrite

Provides bulk write operation functionality.

db.collection.countReturns a count of the number of documents in a collection or a view.
db.collection.countDocumentsReturns a count of the number of documents in a collection or a view. Wraps the $group aggregation stage with a $sum expression.
db.collection.estimatedDocumentCountReturns an approximate count of the documents in a collection or a view.
db.collection.createIndexBuilds an index on a collection.
db.collection.createIndexesBuilds one or more indexes on a collection.
db.collection.dataSizeReturns the size of the collection. Wraps the size field in the output of the collStats.
db.collection.deleteOneDeletes a single document in a collection.
db.collection.deleteManyDeletes multiple documents in a collection.
db.collection.distinctReturns an array of documents that have distinct values for the specified field.
db.collection.dropRemoves the specified collection from the database.
db.collection.dropIndexRemoves a specified index on a collection.
db.collection.dropIndexesRemoves all indexes on a collection.
db.collection.ensureIndex

Deprecated. Use db.collection.createIndex.

db.collection.explainReturns information on the query execution of various methods.
db.collection.findPerforms a query on a collection or a view and returns a cursor object.
db.collection.findAndModifyAtomically modifies and returns a single document.
db.collection.findOnePerforms a query and returns a single document.
db.collection.findOneAndDeleteFinds a single document and deletes it.
db.collection.findOneAndReplaceFinds a single document and replaces it.
db.collection.findOneAndUpdateFinds a single document and updates it.
db.collection.getIndexes

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

db.collection.getShardDistributionPrints the data distribution statistics for a sharded collection.
db.collection.getShardVersionProvides a wrapper for the database command getShardVersion.
db.collection.insertOneInserts a new document in a collection.
db.collection.insertManyInserts several new document in a collection.
db.collection.isCappedReports if a collection is a capped collection.
db.collection.mapReduceRuns map-reduce aggregation operations on a collection.
db.collection.reIndexRebuilds all existing indexes on a collection.
db.collection.renameCollectionChanges the name of a collection.
db.collection.replaceOneReplaces a single document in a collection.
db.collection.statsReports on the state of a collection. Provides a wrapper around the collStats.
db.collection.storageSizeReports the total size used by the collection in bytes. Provides a wrapper around the storageSize field of the collStats output.
db.collection.totalIndexSizeReports the total size used by the indexes on a collection. Provides a wrapper around the totalIndexSize field of the collStats output.
db.collection.totalSizeReports the total size of a collection, including the size of all documents and all indexes on a collection.
db.collection.updateOneModifies a single document in a collection.
db.collection.updateManyModifies multiple documents in a collection.
db.collection.validateValidates a collection.
db.collection.watchOpens a change stream cursor on the collection.
MethodDescription
Mongo

JavaScript constructor to instantiate a database connection from the mongo shell or from a JavaScript file.

The Mongo method has the following parameters:

ParameterTypeDescription
hoststring

Optional

The connection string for the target database connection.

If omitted, Mongo instantiates a connection to the localhost interface on the default port 27017.

ClientSideFieldLevelEncryptionOptionsDocument

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.

Mongo.getDBReturns a database object.
Mongo.setReadPrefSets the read preference for the MongoDB connection.
Mongo.watchOpens 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.
MethodDescription
cursor.addOptionAdds special wire protocol flags that modify the behavior of the query.
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.

The following example query returns results in batches of 100:

db.myCollection.find().batchSize(100)
cursor.closeClose a cursor and free associated server resources.
cursor.collationSpecifies the collation for the cursor returned by the db.collection.find.
cursor.commentAttaches a comment to the query to allow for traceability in the logs and the system.profile collection.
cursor.countModifies the cursor to return the number of documents in the result set rather than the documents themselves.
cursor.explainReports on the query execution plan for a cursor.
cursor.forEachApplies a JavaScript function for every document in a cursor.
cursor.hasNextReturns true if the cursor has documents and can be iterated.
cursor.hintForces MongoDB to use a specific index for a query.
cursor.isClosedReturns true if the cursor is closed.
cursor.isExhaustedReturns true if the cursor is closed and there are no objects remaining in the batch.
cursor.itcountComputes the total number of documents in the cursor client-side by fetching and iterating the result set.
cursor.limitConstrains the size of a cursor's result set.
cursor.mapApplies a function to each document in a cursor and collects the return values in an array.
cursor.maxSpecifies an exclusive upper index bound for a cursor. For use with cursor.hint
cursor.maxTimeMSSpecifies a cumulative time limit in milliseconds for processing operations on a cursor.
cursor.minSpecifies an inclusive lower index bound for a cursor. For use with cursor.hint
cursor.nextReturns the next document in a cursor.
cursor.noCursorTimeout

Instructs the server to avoid closing a cursor automatically after a period of inactivity.

cursor.objsLeftInBatchReturns the number of documents left in the current cursor batch.
cursor.readConcernSpecifies a read concern for a db.collection.find operation.
cursor.readPrefSpecifies a read preference to a cursor to control how the client directs queries to a replica set.
cursor.returnKeyModifies the cursor to return index keys rather than the documents.
cursor.showRecordIdAdds an internal storage engine ID field to each document returned by the cursor.
cursor.sizeReturns a count of the documents in the cursor after applying skip and limit methods.
cursor.skipReturns a cursor that begins returning results only after passing or skipping a number of documents.
cursor.sortReturns results ordered according to a sort specification.
cursor.tailableMarks the cursor as tailable. Only valid for cursors over capped collections.
cursor.toArrayReturns an array that contains all documents returned by the cursor.
MethodDescription
db.aggregateRuns admin/diagnostic pipeline which does not require an underlying collection.
db.createCollectionCreates a new collection or view.
db.createViewCreates a view as the result of applying the specified aggregation pipeline to the source collection or view.
db.commandHelpDisplays help text for the specified database command.
db.dropDatabaseRemoves the current database.
db.getCollectionReturns a collection or view object. Used to access collections with names that are not valid in the mongo shell.
db.getCollectionInfosReturns collection information for all collections and views in the current database.
db.getCollectionNamesLists all collections and views in the current database.
db.getLastErrorChecks and returns the status of the last operation. Wraps getLastError.
db.getLastErrorObjReturns the status document for the last operation. Wraps getLastError.
db.getMongoReturns the current database connection.
db.getLogComponentsReturns the current log verbosity settings.
db.getNameReturns the name of the current database.
db.getProfilingStatusReturns the current profile level, slowOpThresholdMs setting, and slowOpSampleRate setting.
db.getSiblingDBProvides access to the specified database.
db.listCommandsProvides a list of all database commands.
db.logoutEnds an authenticated session.
db.printShardingStatusPrints a formatted report of the sharding configuration and the information regarding existing chunks in a sharded cluster.
db.runCommandRuns a database command.
db.setLogLevelSets a single verbosity level for log messages.
db.setProfilingLevelConfigures the database profiler level, slowms, and sampleRate.
db.watchOpens 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.

Info With Circle IconCreated with Sketch.Note

Free cloud monitoring is only available for MongoDB Community Edition.

MethodDescription
db.disableFreeMonitoringDisables free cloud monitoring for your deployment.
db.enableFreeMonitoringEnables free cloud monitoring for your deployment.
db.getFreeMonitoringStatusReturns the free cloud monitoring status for your deployment.
Info With Circle IconCreated with Sketch.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.
MethodDescription
ClientEncryption.decryptDecrypts 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.
ClientEncryption.encryptEncrypts the specified value using the specified encryptionKeyId and encryptionAlgorithm.
getClientEncryptionReturns the ClientEncryption object for the current database collection.
getKeyVaultReturns the KeyVault object for the current database connection.
KeyVault.addKeyAlternateNameAdds the keyAltName to the keyAltNames array of the data encryption key with the specified UUID.
KeyVault.createKeyAdds a data encryption key to the key vault associated to the database connection.
KeyVault.deleteKeyDeletes a data encryption key with the specified UUID from the key vault associated to the database connection.
KeyVault.getKeyGets a data encryption key with the specified UUID. The data encryption key must exist in the key vault associated to the database connection.
KeyVault.getKeyByAltNameGets all data encryption keys with the specified keyAltName.
KeyVault.getKeysReturns all data encryption keys stored in the key vault associated to the database connection.
KeyVault.removeKeyAlternateNameRemoves 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.
MethodDescription
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.
MethodDescription
db.collection.getPlanCacheReturns an interface to access the query plan cache object and associated PlanCache methods for a collection.
PlanCache.clearRemoves all cached query plans for a collection.
PlanCache.clearPlansByQueryClears the cached query plans for the specified query shape.
PlanCache.helpLists the methods available to view and modify a collection’s query plan cache.
PlanCache.listReturns an array of plan cache entries for a collection.
MethodDescription
rs.addAdds a member to the replica set. You must connect to the primary of the replica set to run this method.
rs.addArbAdds an arbiter to an existing replica set.
rs.configReturns a document that contains the current replica set configuration.
rs.freezeMakes the replica set member that mongosh is connected to ineligible to become primary for the specified duration. You must specify the duration in seconds.
db.getReplicationInfoReturns the status of the replica set from the oplog data.
rs.initiateInitializes a new replica set.
rs.isMaster()

Returns the replica set configuration, role, and status for the mongod instance that mongosh is connected to.

The mongosh rs.isMaster() method wraps the server isMaster command.

db.printReplicationInfoReturns the oplog of the replica set member that mongosh is connected to.
rs.printReplicationInfoReturns 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 '
}
rs.reconfig()Modifies the configuration of an existing replica set.
rs.removeRemoves the member specified by hostname from the replica set.
rs.statusReturns the status of the replica set member that mongosh is connected to.
rs.stepDownMakes the primary of the replica set a secondary. You must be connected to the primary to run this method.
rs.syncFromResets the sync target to the replica set member specified by hostname for the replica set member that mongosh is connected to.
MethodDescription
db.createRoleCreates a role and specifies its privileges.
db.dropRoleDeletes a user-defined role.
db.dropAllRolesDeletes all user-defined roles associated with a database.
db.getRoleReturns information for the specified role.
db.getRolesReturns information for all the user-defined roles in a database.
db.grantPrivilegesToRoleAssigns privileges to a user-defined role.
db.revokePrivilegesFromRoleRemoves the specified privileges from a user-defined role.
db.grantRolesToRoleSpecifies roles from which a user-defined role inherits privileges.
db.revokeRolesFromRoleRemoves inherited roles from a role.
db.updateRoleUpdates a user-defined role.
MethodDescription
Mongo.startSessionStarts a session for the connection.
Session.advanceOperationTime()Updates the operation time.
Session.endSession()Ends the session.
Session.getClusterTime()Returns the most recent cluster time as seen by the session.
Session.getDatabase()Access the specified database from the session in the shell.
Session.getOperationTime()Returns the timestamp of the last acknowledged operation for the session.
Session.getOptions()Returns the options for the session.
Session.hasEnded()Returns a boolean that specifies whether the session has ended.
SessionOptionsThe options for a session in the shell. To access the SessionOptions object, use Session.getOptions.
MethodDescription
db.hostInfoReturns a document with information about the system running the MongoDB instance.
db.isMaster

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

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

db.collection.latencyStatsReturns latency statistics for a specified collection.
db.printCollectionStatsReturns statistics from every collection.
db.serverBuildInfoReturns a document that displays the compilation parameters for the mongod instance.
db.serverCmdLineOptsReturns a document with information about the runtime options used to start the MongoDB instance.
db.serverStatusReturns a document that provides an overview of the database process.
db.statsReturns a document that reports on the state of the current database.
db.versionReturns the version of the mongod instance.
MethodDescription
sh.addShardAdds a shard to a sharded cluster.
sh.addShardTagAliases to sh.addShardToZone.
sh.addShardToZoneAssociates a shard with a zone. Supports configuring zones in sharded clusters.
sh.addTagRangeAliases to sh.updateZoneKeyRange.
sh.balancerCollectionStatus

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

New in version 4.4.

sh.disableAutoSplitDisables auto-splitting for the sharded cluster.
sh.disableBalancingDisables balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.
sh.enableAutoSplitEnables auto-splitting for the sharded cluster.
sh.enableBalancingActivates the sharded collection balancer process if previously disabled using sh.disableBalancing.
sh.enableShardingEnables sharding on a specific database.
sh.getBalancerStateReturns a boolean to report if the balancer is currently enabled.
sh.isBalancerRunningReturns a boolean to report if the balancer process is currently migrating chunks.
sh.moveChunkMigrates a chunk in a sharded cluster.
sh.removeRangeFromZoneRemoves the association between a range of shard key values and a zone.
sh.removeShardFromZoneRemoves the association between a shard and a zone.
sh.removeShardTagRemoves the association between a tag and a shard.
sh.removeTagRangeRemoves 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.
sh.setBalancerStateEnables or disables the balancer which migrates chunks between shards.
sh.shardCollectionEnables sharding for a collection.
sh.splitAtDivides an existing chunk into two chunks using a specific value of the shard key as the dividing point.
sh.splitFindDivides an existing chunk that contains a document matching a query into two approximately equal chunks.
sh.startBalancerEnables the balancer.
sh.statusReports on the status of a sharded cluster.
sh.stopBalancerDisables the balancer. This operation does not wait for the balancer to complete any in progress operations, and may terminate ongoing operations.
sh.updateZoneKeyRangeAssociates a range of shard keys with a zone. Supports configuring zones in sharded clusters.
MethodDescription
Session.abortTransactionTerminates a multi-document transaction and rolls back any data changes made by the operations within the transaction.
Session.commitTransactionSaves the changes made by the operations in a multi-document transaction and ends the transaction.
Session.startTransactionStarts a multi-document transaction associated with the session.
Important With Circle IconCreated with Sketch.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:

MethodDescription
db.authAuthenticates a user to a database.
db.changeUserPasswordChanges an existing user’s password.
db.createUserCreates a new user.
db.dropAllUsersDeletes all users associated with a database.
db.dropUserDeletes a single user.
db.getUserReturns information about the specified user.
db.getUsersReturns information about all users associated with a database.
db.updateUserUpdates a specified user's data.
db.grantRolesToUserGrants a role and its privileges to a user.
db.revokeRolesFromUserRemoves a role from a user.
Give Feedback