Navigation

Database Commands

All command documentation outlined below describes a command and its available parameters and provides a document template or prototype for each command. Some command documentation also includes the relevant mongosh helpers.

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

db.runCommand( { <command> } )

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

db.adminCommand( { <command> } )

Note

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

Command Syntax

When you run a database command, you specify the command as a document to db.runCommand(). The document’s key is the command to run, and the value is typically supplied as 1. The value does not affect the output of the command for example:

db.runCommand( { hello: 1 } )

User Commands

Aggregation Commands

Name Description
aggregate Performs aggregation tasks such as $group using an aggregation pipeline.
count Counts the number of documents in a collection or a view.
distinct Displays the distinct values found for a specified key in a collection or a view.
mapReduce Performs map-reduce aggregation for large data sets.

Geospatial Commands

Name Description
geoSearch Removed in MongoDB 5.0. Performs a geospatial query that uses MongoDB’s haystack index functionality.

Query and Write Operation Commands

Name Description
delete Deletes one or more documents.
find Selects documents in a collection or a view.
findAndModify Returns and modifies a single document.
getMore Returns batches of documents currently pointed to by the cursor.
insert Inserts one or more documents.
resetError Removed in MongoDB 5.0. Resets the last error status.
update Updates one or more documents.

Query Plan Cache Commands

Name Description
planCacheClear Removes cached query plan(s) for a collection.
planCacheClearFilters Clears index filter(s) for a collection.
planCacheListFilters Lists the index filters for a collection.
planCacheSetFilter Sets an index filter for a collection.

Database Operations

Authentication Commands

Name Description
authenticate Starts an authenticated session using a username and password.
getnonce This is an internal command to generate a one-time password for authentication.
logout Terminates the current authenticated session.

User Management Commands

Name Description
createUser Creates a new user.
dropAllUsersFromDatabase Deletes all users associated with a database.
dropUser Removes a single user.
grantRolesToUser Grants a role and its privileges to a user.
revokeRolesFromUser Removes a role from a user.
updateUser Updates a user’s data.
usersInfo Returns information about the specified users.

Role Management Commands

Name Description
createRole Creates a role and specifies its privileges.
dropRole Deletes the user-defined role.
dropAllRolesFromDatabase Deletes all user-defined roles from a database.
grantPrivilegesToRole Assigns privileges to a user-defined role.
grantRolesToRole Specifies roles from which a user-defined role inherits privileges.
invalidateUserCache Flushes the in-memory cache of user information, including credentials and roles.
revokePrivilegesFromRole Removes the specified privileges from a user-defined role.
revokeRolesFromRole Removes specified inherited roles from a user-defined role.
rolesInfo Returns information for the specified role or roles.
updateRole Updates a user-defined role.

Replication Commands

Name Description
applyOps Internal command that applies oplog entries to the current data set.
hello Displays information about this member’s role in the replica set, including whether it is the primary.
replSetAbortPrimaryCatchUp Forces the elected primary to abort sync (catch up) then complete the transition to primary.
replSetFreeze Prevents the current member from seeking election as primary for a period of time.
replSetGetConfig Returns the replica set’s configuration object.
replSetGetStatus Returns a document that reports on the status of the replica set.
replSetInitiate Initializes a new replica set.
replSetMaintenance Enables or disables a maintenance mode, which puts a secondary node in a RECOVERING state.
replSetReconfig Applies a new configuration to an existing replica set.
replSetResizeOplog Dynamically resizes the oplog for a replica set member. Available for WiredTiger storage engine only.
replSetStepDown Forces the current primary to step down and become a secondary, forcing an election.
replSetSyncFrom Explicitly override the default logic for selecting a member to replicate from.

See also

Replication for more information regarding replication.

Sharding Commands

Name Description
abortReshardCollection

Aborts a resharding operation.

New in version 5.0.

addShard Adds a shard to a sharded cluster.
addShardToZone Associates a shard with a zone. Supports configuring zones in sharded clusters.
balancerCollectionStatus

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

New in version 4.4.

balancerStart Starts a balancer thread.
balancerStatus Returns information on the balancer status.
balancerStop Stops the balancer thread.
checkShardingIndex Internal command that validates index on shard key.
clearJumboFlag Clears the jumbo flag for a chunk.
cleanupOrphaned Removes orphaned data with shard key values outside of the ranges of the chunks owned by a shard.
cleanupReshardCollection

Cleans up a failed resharding operation.

New in version 5.0.

commitReshardCollection

Forces a resharding operation to block writes and complete.

New in version 5.0.

configureCollectionBalancing

Configures balancer settings on a sharded collection.

New in version 5.3.

enableSharding Creates a database.
flushRouterConfig Forces a mongod/mongos instance to update its cached routing metadata.
getShardMap Internal command that reports on the state of a sharded cluster.
getShardVersion Internal command that returns the config server version.
isdbgrid Verifies that a process is a mongos.
listShards Returns a list of configured shards.
medianKey Deprecated internal command. See splitVector.
moveChunk Internal command that migrates chunks between shards.
movePrimary Reassigns the primary shard when removing a shard from a sharded cluster.
mergeChunks Provides the ability to combine chunks on a single shard.
refineCollectionShardKey

Refines a collection’s shard key by adding a suffix to the existing key.

New in version 4.4.

removeShard Starts the process of removing a shard from a sharded cluster.
removeShardFromZone Removes the association between a shard and a zone. Supports configuring zones in sharded clusters.
reshardCollection

Initiates a resharding operation to change the shard key for a collection, changing the distribution of your data.

New in version 5.0.

setShardVersion Internal command to sets the config server version.
shardCollection Enables the sharding functionality for a collection, allowing the collection to be sharded.
shardingState Reports whether the mongod is a member of a sharded cluster.
split Creates a new chunk.
splitVector Internal command that determines split points.
unsetSharding Removed in MongoDB 5.0. Internal command that affects connections between instances in a MongoDB deployment.
updateZoneKeyRange Adds 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’s sharding functionality.

Session Commands

Command Description
abortTransaction

Abort transaction.

New in version 4.0.

commitTransaction

Commit transaction.

New in version 4.0.

endSessions Expire sessions before the sessions’ timeout period.
killAllSessions Kill all sessions.
killAllSessionsByPattern Kill all sessions that match the specified pattern
killSessions Kill specified sessions.
refreshSessions Refresh idle sessions.
startSession Starts a new session.

Administration Commands

Diagnostic Commands

Name Description
buildInfo Displays statistics about the MongoDB build.
collStats Reports storage utilization statics for a specified collection.
connPoolStats Reports statistics on the outgoing connections from this MongoDB instance to other MongoDB instances in the deployment.
connectionStatus Reports the authentication state for the current connection.
cursorInfo Removed in MongoDB 3.2. Replaced with metrics.cursor.
dataSize Returns the data size for a range of data. For internal use.
dbHash Returns hash value a database and its collections.
dbStats Reports storage utilization statistics for the specified database.
driverOIDTest Internal command that converts an ObjectId to a string to support tests.
explain Returns information on the execution of various operations.
features Reports on features available in the current MongoDB instance.
getCmdLineOpts Returns a document with the run-time arguments to the MongoDB instance and their parsed options.
getLog Returns recent log messages.
hostInfo Returns data that reflects the underlying host system.
_isSelf Internal command to support testing.
listCommands Lists all database commands provided by the current mongod instance.
lockInfo Internal command that returns information on locks that are currently being held or pending. Only available for mongod instances.
netstat Internal command that reports on intra-deployment connectivity. Only available for mongos instances.
ping Internal command that tests intra-deployment connectivity.
profile Interface for the database profiler.
serverStatus Returns a collection metrics on instance-wide resource utilization and status.
shardConnPoolStats Removed in MongoDB 5.0. Use connPoolStats instead.
top Returns raw usage statistics for each database in the mongod instance.
validate Internal command that scans for a collection’s data and indexes for correctness.
whatsmyuri Internal command that returns information on the current client.

Free Monitoring Commands

Name Description
setFreeMonitoring Enables/disables free monitoring during runtime.

Auditing Commands

Name Description
logApplicationMessage Posts a custom message to the audit log.
Search Results
    Was this page helpful?