Database Commands

All command documentation outlined below describes a command andits available parameters and provides a document template or prototypefor each command. Some command documentation also includes the relevantmongo shell helpers.

To run a command against the current database, use db.runCommand():

  1. db.runCommand( { <command> } )

To run an administrative command against the admin database, use db.adminCommand():

  1. db.adminCommand( { <command> } )

Note

For details on specific commands, including syntax and examples,click on the specific command to go to its reference page.

User Commands

Aggregation Commands

NameDescription
aggregatePerforms aggregation tasks such as group using the aggregation framework.
countCounts the number of documents in a collection or a view.
distinctDisplays the distinct values found for a specified key in a collection or a view.
mapReducePerforms map-reduce aggregation for large data sets.

Geospatial Commands

NameDescription
geoSearchPerforms a geospatial query that uses MongoDB’s haystack index functionality.

Query and Write Operation Commands

NameDescription
deleteDeletes one or more documents.
findSelects documents in a collection or a view.
findAndModifyReturns and modifies a single document.
getLastErrorReturns the success status of the last operation.
getMoreReturns batches of documents currently pointed to by the cursor.
getPrevErrorReturns status document containing all errors since the last resetError command.
insertInserts one or more documents.
resetErrorResets the last error status.
updateUpdates one or more documents.

Query Plan Cache Commands

NameDescription
planCacheClearRemoves cached query plan(s) for a collection.
planCacheClearFiltersClears index filter(s) for a collection.
planCacheListFiltersLists the index filters for a collection.
planCacheListPlansDisplays the cached query plans for the specified query shape.
planCacheListQueryShapesDisplays the query shapes for which cached query plans exist.
planCacheSetFilterSets an index filter for a collection.

Database Operations

Authentication Commands

NameDescription
authenticateStarts an authenticated session using a username and password.
getnonceThis is an internal command to generate a one-time password for authentication.
logoutTerminates the current authenticated session.

User Management Commands

NameDescription
createUserCreates a new user.
dropAllUsersFromDatabaseDeletes all users associated with a database.
dropUserRemoves a single user.
grantRolesToUserGrants a role and its privileges to a user.
revokeRolesFromUserRemoves a role from a user.
updateUserUpdates a user’s data.
usersInfoReturns information about the specified users.

Role Management Commands

NameDescription
createRoleCreates a role and specifies its privileges.
dropRoleDeletes the user-defined role.
dropAllRolesFromDatabaseDeletes all user-defined roles from a database.
grantPrivilegesToRoleAssigns privileges to a user-defined role.
grantRolesToRoleSpecifies roles from which a user-defined role inherits privileges.
invalidateUserCacheFlushes the in-memory cache of user information, including credentials and roles.
revokePrivilegesFromRoleRemoves the specified privileges from a user-defined role.
revokeRolesFromRoleRemoves specified inherited roles from a user-defined role.
rolesInfoReturns information for the specified role or roles.
updateRoleUpdates a user-defined role.

Replication Commands

NameDescription
applyOpsInternal command that applies oplog entries to the current data set.
isMasterDisplays information about this member’s role in the replica set, including whether it is the master.
replSetAbortPrimaryCatchUpForces the elected primary to abort sync (catch up) then complete the transition to primary.
replSetFreezePrevents the current member from seeking election as primary for a period of time.
replSetGetConfigReturns the replica set’s configuration object.
replSetGetStatusReturns a document that reports on the status of the replica set.
replSetInitiateInitializes a new replica set.
replSetMaintenanceEnables or disables a maintenance mode, which puts a secondary node in a RECOVERING state.
replSetReconfigApplies a new configuration to an existing replica set.
replSetResizeOplogDynamically resizes the oplog for a replica set member. Available for WiredTiger storage engine only.
replSetStepDownForces the current primary to step down and become a secondary, forcing an election.
replSetSyncFromExplicitly override the default logic for selecting a member to replicate from.

See also

Replication for more information regardingreplication.

Sharding Commands

NameDescription
addShardAdds a shard to a sharded cluster.
addShardToZoneAssociates a shard with a zone. Supports configuring zones in sharded clusters.
balancerStartStarts a balancer thread.
balancerStatusReturns information on the balancer status.
balancerStopStops the balancer thread.
checkShardingIndexInternal command that validates index on shard key.
cleanupOrphanedRemoves orphaned data with shard key values outside of the ranges of the chunks owned by a shard.
enableShardingEnables sharding on a specific database.
flushRouterConfigForces a mongod/mongos instance to update its cached routing metadata.
getShardMapInternal command that reports on the state of a sharded cluster.
getShardVersionInternal command that returns the config server version.
isdbgridVerifies that a process is a mongos.
listShardsReturns a list of configured shards.
medianKeyDeprecated internal command. See splitVector.
moveChunkInternal command that migrates chunks between shards.
movePrimaryReassigns the primary shard when removing a shard from a sharded cluster.
mergeChunksProvides the ability to combine chunks on a single shard.
removeShardStarts the process of removing a shard from a sharded cluster.
removeShardFromZoneRemoves the association between a shard and a zone. Supports configuring zones in sharded clusters.
setShardVersionInternal command to sets the config server version.
shardCollectionEnables the sharding functionality for a collection, allowing the collection to be sharded.
shardingStateReports whether the mongod is a member of a sharded cluster.
splitCreates a new chunk.
splitChunkInternal command to split chunk. Instead use the methods sh.splitFind() and sh.splitAt().
splitVectorInternal command that determines split points.
unsetShardingInternal command that affects connections between instances in a MongoDB deployment.
updateZoneKeyRangeAdds or removes the association between a range of sharded data and a zone. Supports configuring zones in sharded clusters.

See also

Sharding for more information about MongoDB’ssharding functionality.

Session Commands

CommandsDescriptions
abortTransactionAbort transaction.New in version 4.0.
commitTransactionCommit transaction.New in version 4.0.
endSessionsExpire sessions before the sessions’ timeout period.New in version 3.6.
killAllSessionsKill all sessions.New in version 3.6.
killAllSessionsByPatternKill all sessions that match the specified patternNew in version 3.6.
killSessionsKill specified sessions.New in version 3.6.
refreshSessionsRefresh idle sessions.New in version 3.6.
startSessionStarts a new session.New in version 3.6.

Administration Commands

NameDescription
cleanInternal namespace administration command.
cloneCollectionCopies a collection from a remote host to the current host.
cloneCollectionAsCappedCopies a non-capped collection as a new capped collection.
collModAdd options to a collection or modify a view definition.
compactDefragments a collection and rebuilds the indexes.
connPoolSyncInternal command to flush connection pool.
convertToCappedConverts a non-capped collection to a capped collection.
createCreates a collection or a view.
createIndexesBuilds one or more indexes for a collection.
currentOpReturns a document that contains information on in-progress operations for the database instance.
dropRemoves the specified collection from the database.
dropDatabaseRemoves the current database.
dropConnectionsDrops outgoing connections to the specified list of hosts.
dropIndexesRemoves indexes from a collection.
filemd5Returns the md5 hash for files stored using GridFS.
fsyncFlushes pending writes to the storage layer and locks the database to allow backups.
fsyncUnlockUnlocks one fsync lock.
getParameterRetrieves configuration options.
killCursorsKills the specified cursors for a collection.
killOpTerminates an operation as specified by the operation ID.
listCollectionsReturns a list of collections in the current database.
listDatabasesReturns a document that lists all databases and returns basic database statistics.
listIndexesLists all indexes for a collection.
logRotateRotates the MongoDB logs to prevent a single file from taking too much space.
reIndexRebuilds all indexes on a collection.
renameCollectionChanges the name of an existing collection.
setFeatureCompatibilityVersionEnables or disables features that persist data that are backwards-incompatible.
setParameterModifies configuration options.
shutdownShuts down the mongod or mongos process.

Diagnostic Commands

NameDescription
availableQueryOptionsInternal command that reports on the capabilities of the current MongoDB instance.
buildInfoDisplays statistics about the MongoDB build.
collStatsReports storage utilization statics for a specified collection.
connPoolStatsReports statistics on the outgoing connections from this MongoDB instance to other MongoDB instances in the deployment.
connectionStatusReports the authentication state for the current connection.
cursorInfoRemoved in MongoDB 3.2. Replaced with metrics.cursor.
dataSizeReturns the data size for a range of data. For internal use.
dbHashReturns hash value a database and its collections.
dbStatsReports storage utilization statistics for the specified database.
diagLoggingRemoved in MongoDB 3.6. To capture, replay, and profile commands sent to your MongoDB deployment, use mongoreplay.
driverOIDTestInternal command that converts an ObjectId to a string to support tests.
explainReturns information on the execution of various operations.
featuresReports on features available in the current MongoDB instance.
getCmdLineOptsReturns a document with the run-time arguments to the MongoDB instance and their parsed options.
getLogReturns recent log messages.
hostInfoReturns data that reflects the underlying host system.
isSelfInternal command to support testing.
listCommandsLists all database commands provided by the current mongod instance.
netstatInternal command that reports on intra-deployment connectivity. Only available for mongos instances.
pingInternal command that tests intra-deployment connectivity.
profileInterface for the database profiler.
serverStatusReturns a collection metrics on instance-wide resource utilization and status.
shardConnPoolStatsReports statistics on a mongos’s connection pool for clientoperations against shards.
topReturns raw usage statistics for each database in the mongod instance.
validateInternal command that scans for a collection’s data and indexes for correctness.
whatsmyuriInternal command that returns information on the current client.

Free Monitoring Commands

NameDescription
setFreeMonitoringEnables/disables free monitoring during runtime.

Auditing Commands

NameDescription
logApplicationMessagePosts a custom message to the audit log.