Database Manual / Reference

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.下面列出的所有命令文档都描述了命令及其可用参数,并为每个命令提供了文档模板或原型。一些命令文档还包括相关的mongosh助手。

To run a command against the current database, use db.runCommand():要对当前数据库运行命令,请使用db.runCommand()

db.runCommand( { <command> } )

To run an administrative command against the admin database, use db.adminCommand():要对admin数据库运行管理命令,请使用db.adminCommand()

db.adminCommand( { <command> } )

Note

For details on a specific command, including syntax and examples, click on the link to the command's 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()的文档。文档的键是要运行的命令,其值通常为1。该值不会影响命令的输出,例如:

db.runCommand( { hello: 1 } )

User Commands用户命令

Aggregation Commands聚合命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
aggregatePerforms aggregation tasks such as $group using an aggregation pipeline.使用聚合管道执行聚合任务,如$groupLimited support for M0 and Flex clusters.M0和Flex集群的支持有限。
countCounts the number of documents in a collection or a view.统计集合或视图中的文档数。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。
distinctDisplays the distinct values found for a specified key in a collection or a view.显示集合或视图中指定键的不同值。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。
mapReducePerforms map-reduce aggregation for large data sets.对大型数据集执行map-reduce聚合。No support for M0 and Flex clusters.不支持M0和Flex集群

Query and Write Operation Commands查询和写入操作命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
bulkWritePerforms many insert, update, and delete operations on multiple collections in one request.在一个请求中对多个集合执行许多插入、更新和删除操作。
New in version 8.0.8.0版本中的新功能。
Yes支持
deleteDeletes one or more documents.删除一个或多个文档。Yes支持
findSelects documents in a collection or a view.选择集合或视图中的文档。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。
findAndModifyReturns and modifies a single document.返回并修改单个文档。Yes支持
insertInserts one or more documents.插入一个或多个文档。Yes支持
updateUpdates one or more documents.更新一个或多个文档。Yes支持

Query Plan Cache Commands查询计划缓存命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
planCacheClearRemoves cached query plan(s) for a collection.删除集合的缓存查询计划。No support for M0 and Flex clusters.不支持M0和Flex集群
planCacheClearFiltersClears index filter(s) for a collection.清除集合的索引筛选器。No support for M0 and Flex clusters.不支持M0和Flex集群
planCacheListFiltersLists the index filters for a collection.列出集合的索引筛选器。No support for M0 and Flex clusters.不支持M0和Flex集群
planCacheSetFilterSets an index filter for a collection.为集合设置索引筛选器。No support for M0 and Flex clusters.不支持M0和Flex集群

Database Operations数据库操作

Authentication Commands身份验证命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
authenticateStarts an authenticated session using a username and password.使用用户名和密码启动经过身份验证的会话。No support for M0 and Flex clusters.不支持M0和Flex集群
logoutTerminates the current authenticated session.终止当前经过身份验证的会话。Yes支持

User Management Commands用户管理命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
createUserCreates a new user.创建新用户。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
dropAllUsersFromDatabaseDeletes all users associated with a database.删除与数据库关联的所有用户。No support for M0 and Flex clusters.不支持M0和Flex集群
dropUserRemoves a single user.删除单个用户。No support for M10 clusters.不支持M10集群
grantRolesToUserGrants a role and its privileges to a user.向用户授予角色及其权限。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
revokeRolesFromUserRemoves a role from a user.从用户中删除角色。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
updateUserUpdates a user's data.更新用户的数据。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
usersInfoReturns information about the specified users.返回有关指定用户的信息。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。

Role Management Commands角色管理命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
createRoleCreates a role and specifies its privileges.创建角色并指定其权限。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
dropRoleDeletes the user-defined role.删除用户定义的角色。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
dropAllRolesFromDatabaseDeletes all user-defined roles from a database.从数据库中删除所有用户定义的角色。No support for M0 and Flex clusters.不支持M0和Flex集群
grantPrivilegesToRoleAssigns privileges to a user-defined role.为用户定义的角色分配权限。No support for M0 and Flex clusters.不支持M0和Flex集群
grantRolesToRoleSpecifies roles from which a user-defined role inherits privileges.指定用户定义角色从中继承权限的角色。No support for M0 and Flex clusters.不支持M0和Flex集群
invalidateUserCacheFlushes the in-memory cache of user information, including credentials and roles.刷新内存中的用户信息缓存,包括凭据和角色。No support for M0 and Flex clusters.不支持M0和Flex集群
revokePrivilegesFromRoleRemoves the specified privileges from a user-defined role.从用户定义的角色中删除指定的权限。No support for M0 and Flex clusters.不支持M0和Flex集群
revokeRolesFromRoleRemoves specified inherited roles from a user-defined role.从用户定义的角色中删除指定的继承角色。No support for M0 and Flex clusters.不支持M0和Flex集群
rolesInfoReturns information for the specified role or roles.返回指定角色的信息。Yes支持
updateRoleUpdates a user-defined role.更新用户定义的角色。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群

Replication Commands复制命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
appendOplogNoteWrites a non-operational entry to the oplog.将非操作性条目写入oplogNo support for M0 and Flex clusters.不支持M0和Flex集群
applyOpsInternal command that applies oplog entries to the current data set.oplog条目应用于当前数据集的内部命令。Yes支持
helloDisplays information about this member's role in the replica set, including whether it is the primary.显示有关此成员在副本集中的角色的信息,包括它是否为主成员。Yes支持
replSetAbortPrimaryCatchUpForces the elected primary to abort sync (catch up) then complete the transition to primary.强制选定的primary中止同步(追赶),然后完成向primary的转换。Yes支持
replSetFreezePrevents the current member from seeking election as primary for a period of time.阻止当前成员在一段时间内寻求primaryNo support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
replSetGetConfigReturns the replica set's configuration object.返回副本集的配置对象。No support for M0 and Flex clusters.不支持M0和Flex集群
replSetGetStatusReturns a document that reports on the status of the replica set.返回一个报告副本集状态的文档。No support for M0 and Flex clusters.不支持M0和Flex集群
replSetInitiateInitializes a new replica set.初始化新的副本集。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
replSetMaintenanceEnables or disables a maintenance mode, which puts a secondary node in a RECOVERING state.启用或禁用维护模式,该模式使secondary节点处于RECOVERING状态。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
replSetReconfigApplies a new configuration to an existing replica set.将新配置应用于现有副本集。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
replSetResizeOplogDynamically resizes the oplog for a replica set member. Available for WiredTiger storage engine only.动态调整副本集成员的oplog大小。仅适用于WiredTiger存储引擎。No support for M10 clusters.不支持M10集群
replSetStepDownForces the current primary to step down and become a secondary, forcing an election.迫使当前的primary下台,成为secondary,迫使选举。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
replSetSyncFromExplicitly override the default logic for selecting a member to replicate from.显式覆盖用于选择要从中复制的成员的默认逻辑。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群

Tip

Replication for more information regarding replication.请参阅复制以了解有关复制的更多信息。

Sharding Commands分片命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
abortReshardCollectionAborts a resharding operation.中止重分片操作Yes支持
abortMoveCollectionStops an in-progress moveCollection operation.停止正在进行的moveCollection操作。
New in version 8.0.8.0版本中的新功能。
No support for Atlas Shared tier.不支持Atlas共享层
abortUnshardCollectionStops an in-progress unshardCollection operation.停止正在进行的unshardCollection操作。
New in version 8.0.8.0版本中的新功能。
No support for Atlas Shared tier.不支持Atlas共享层
addShardAdds a shard to a sharded cluster.分片添加到分片集群Yes支持
addShardToZoneAssociates a shard with a zone. Supports configuring zones in sharded clusters.将分片与区域关联。支持在分片集群中配置区域Yes支持
analyzeShardKeyCalculates metrics for evaluating a shard key.计算用于评估分片键的指标。
New in version 7.0.7.0版本中的新功能。
Yes支持
balancerCollectionStatusReturns information on whether the chunks of a sharded collection are balanced.返回有关分片集合的块是否平衡的信息。Yes支持
balancerStartStarts a balancer thread.启动平衡器线程。Yes支持
balancerStatusReturns information on the balancer status.返回有关平衡器状态的信息。Yes支持
balancerStopStops the balancer thread.停止平衡器线程。Yes支持
checkMetadataConsistencyPerforms a series of consistency checks on sharding metadata.对分片元数据执行一系列一致性检查。
New in version 7.0.7.0版本中的新功能。
Yes支持
clearJumboFlagClears the jumbo flag for a chunk.清除大块的jumbo标志。Yes支持
cleanupReshardCollectionCleans up a failed resharding operation.清理失败的重分片操作Yes支持
commitReshardCollectionForces a resharding operation to block writes and complete.强制执行重分片操作以阻止写入并完成。Yes支持
configureCollectionBalancingConfigures balancer settings on a sharded collection.配置分片集合上的平衡器设置。Yes支持
configureQueryAnalyzerConfigures query sampling for a collection.为集合配置查询采样。
New in version 7.0.7.0版本中的新功能。
Yes支持
enableShardingCreates a database.创建数据库。Yes支持
flushRouterConfigForces a mongod / mongos instance to update its cached routing metadata.强制mongod/mongos实例更新其缓存的路由元数据。Yes支持
getShardMapInternal command that reports on the state of a sharded cluster.报告分片集群状态的内部命令。No support for M0 and Flex clusters.不支持M0和Flex集群
isdbgridVerifies that a process is a mongos.验证进程是否为mongosYes支持
listShardsReturns a list of configured shards.返回已配置分片的列表。Yes支持
moveChunkInternal command that migrates chunks between shards.在分片之间迁移块的内部命令。Yes支持
movePrimaryReassigns the primary shard when removing a shard from a sharded cluster.从分片集群中删除分片时,重新分配主分片Yes支持
moveRangeMoves ranges between shards.在分片之间移动范围。Yes支持
mergeAllChunksOnShardMerges all mergeable chunks that a shard owns for a given collection.合并一个分片为给定集合拥有的所有可合并块Yes支持
mergeChunksProvides the ability to combine chunks on a single shard.提供在单个分片上组合块的能力。Yes支持
refineCollectionShardKeyRefines a collection's shard key by adding a suffix to the existing key.通过向现有键添加后缀来优化集合的分片键。No support for M10 clusters.不支持M10集群
removeShardStarts the process of removing a shard from a sharded cluster.开始从分片集群中删除分片的过程。No support for M10 clusters.不支持M10集群
removeShardFromZoneRemoves the association between a shard and a zone. Supports configuring zones in sharded clusters.删除分片和区域之间的关联。支持在分片集群中配置区域Yes支持
reshardCollectionInitiates a resharding operation to change the shard key for a collection, changing the distribution of your data.启动重分片操作以更改集合的分片键,从而更改数据的分布。Yes支持
setAllowMigrationsPrevents new automatic migrations on a collection.防止对集合进行新的自动迁移Yes支持
shardCollectionEnables the sharding functionality for a collection, allowing the collection to be sharded.为集合启用分片功能,允许对集合进行分片。Yes支持
shardingStateReports whether the mongod is a member of a sharded cluster.报告mongod是否是分片集群的成员。Yes支持
splitCreates a new chunk.创建新Yes支持
transitionFromDedicatedConfigServerConfigures a dedicated config server to run as a config shard.将专用配置服务器配置为作为配置分片运行。
New in version 8.0.8.0版本中的新功能。
No support for Atlas Shared tier.不支持Atlas共享层
transitionToDedicatedConfigServerConfigures a config shard to run as a dedicated config server.将配置分片配置为作为专用配置服务器运行。
New in version 8.0.8.0版本中的新功能。
No support for Atlas Shared tier.不支持Atlas共享层
unsetShardingRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Internal command that affects connections between instances in a MongoDB deployment.影响MongoDB部署中实例之间连接的内部命令。Yes支持
unshardCollectionUnshards an existing sharded collection and moves the collection data onto a single shard. 解开现有的分片集合,并将集合数据移动到单个分片上。When you unshard a collection, the collection cannot be partitioned across multiple shards and the shard key is removed.当您取消对集合的分区时,该集合不能跨多个分片进行分区,并且分片键将被删除。
New in version 8.0.8.0版本中的新功能。
Yes支持
updateZoneKeyRangeAdds or removes the association between a range of sharded data and a zone. Supports configuring zones in sharded clusters.添加或删除分片数据范围与区域之间的关联。支持在分片集群中配置区域Yes支持

Tip

Sharding for more information about MongoDB's sharding functionality.请参阅分片以了解有关MongoDB分片功能的更多信息。

Session Commands会话命令

Command命令Description描述Atlas Support支持
abortTransactionAbort transaction.中止事务。Yes支持
commitTransactionCommit transaction.提交事务。Yes支持
endSessionsExpire sessions before the sessions' timeout period.在会话超时时间之前过期会话。Yes支持
killAllSessionsKill all sessions.终止所有会话。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
killAllSessionsByPatternKill all sessions that match the specified pattern终止所有符合指定模式的会话No support for M0 and Flex clusters.不支持M0和Flex集群
killSessionsKill specified sessions.终止指定的会话。No support for M0 and Flex clusters.不支持M0和Flex集群
refreshSessionsRefresh idle sessions.刷新空闲会话。Yes支持
startSessionStarts a new session.开始新会话。Yes支持

Administration Commands管理命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
cloneCollectionAsCappedCopies a non-capped collection as a new capped collection.将非上限集合复制为新的封顶集合No support for M0 and Flex clusters.不支持M0和Flex集群
collModAdd options to a collection or modify a view definition.向集合添加选项或修改视图定义。Yes支持
compactDefragments a collection and rebuilds the indexes.对集合进行分片整理并重建索引。No support for M0 and Flex clusters.不支持M0和Flex集群
compactStructuredEncryptionDataCompacts documents specified in the state collections and deletes redundant documents.压缩状态集合中指定的文档并删除冗余文档。Yes支持
convertToCappedConverts a non-capped collection to a capped collection.将非上限集合转换为上限集合。Yes支持
createCreates a collection or a view.创建集合或视图。Yes支持
createIndexesBuilds one or more indexes for a collection.为集合构建一个或多个索引。Yes支持
currentOpReturns a document that contains information on in-progress operations for the database instance.返回一个文档,其中包含有关数据库实例正在进行的操作的信息。Yes支持
dropRemoves the specified collection from the database.从数据库中删除指定的集合。Yes支持
dropDatabaseRemoves the current database.删除当前数据库。Yes支持
dropConnectionsDrops outgoing connections to the specified list of hosts.删除指定主机列表的传出连接。Yes支持
dropIndexesRemoves indexes from a collection.从集合中删除索引。Yes支持
filemd5Deprecated.已弃用。 Returns the md5 hash for files stored using GridFS.返回使用GridFS存储的文件的md5哈希值。Yes支持
fsyncFlushes pending writes to the storage layer and locks the database to allow backups.刷新对存储层的待处理写入,并锁定数据库以允许备份。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
fsyncUnlockUnlocks one fsync lock.解锁一个fsync锁。No support for M0 and Flex clusters.不支持M0和Flex集群
getDefaultRWConcernRetrieves the global default read and write concern options for the deployment.检索部署的全局默认读写入关注选项。Yes支持
getClusterParameterRetrieves cluster parameter values from all nodes in a cluster.从群集中的所有节点检索群集参数值。
New in version 6.0.6.0版本中的新功能。
Yes支持
getParameterRetrieves configuration options.检索配置选项。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。
killCursorsKills the specified cursors for a collection.杀死集合的指定游标。Yes支持
killOpTerminates an operation as specified by the operation ID.根据操作ID指定终止操作。Limited support for M0, M10, and Flex clusters.
listCollectionsReturns a list of collections in the current database.返回当前数据库中的集合列表。Yes支持
listDatabasesReturns a document that lists all databases and returns basic database statistics.返回一个列出所有数据库并返回基本数据库统计信息的文档。Yes支持
listIndexesLists all indexes for a collection.列出集合的所有索引。Yes支持
logRotateRotates the MongoDB logs to prevent a single file from taking too much space.旋转MongoDB日志以防止单个文件占用太多空间。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
reIndexRebuilds all indexes on a collection.重建集合上的所有索引。No support for M0 and Flex clusters.不支持M0和Flex集群
renameCollectionChanges the name of an existing collection.更改现有集合的名称。Yes支持
rotateCertificatesPerforms online TLS certificate rotation.执行在线TLS证书轮换。Yes支持
setFeatureCompatibilityVersionEnables or disables features that persist data that are backwards-incompatible.启用或禁用保留向后不兼容数据的功能。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
setIndexCommitQuorumChanges the minimum number of data-bearing members (i.e commit quorum), including the primary, that must vote to commit an in-progress index build before the primary marks those indexes as ready.更改数据承载成员的最小数量(即提交法定人数),包括主成员,在主成员将这些索引标记为就绪之前,必须投票提交正在进行的索引构建Yes支持
setClusterParameterModifies configuration options for all nodes in a replica set or sharded cluster.修改副本集或分片群集中所有节点的配置选项。
New in version 6.0.6.0版本中的新功能。
Yes支持
setParameterModifies configuration options.修改配置选项。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
setDefaultRWConcernSets the global default read and write concern options for the deployment.设置部署的全局默认读写入关注选项。Yes支持
setUserWriteBlockModeBlocks and unblocks writes to the entire cluster.阻止和解除阻止对整个集群的写入。No
shutdownShuts down the mongod or mongos process.关闭mongodmongos进程。No support for Flex clusters, M0, and M10 clusters.不支持Flex集群、M0M10集群
validateDBMetadataChecks that the stored metadata of a database or a collection is valid within a particular API version.检查数据库或集合的存储元数据在特定的API版本中是否有效。Yes支持

Diagnostic Commands诊断命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
buildInfoDisplays statistics about the MongoDB build.显示有关MongoDB构建的统计信息。Yes支持
collStatsReports storage utilization statics for a specified collection.报告指定集合的存储利用率统计数据。Yes支持
connPoolStatsReports statistics on the outgoing connections from this MongoDB instance to other MongoDB instances in the deployment.报告此MongoDB实例到部署中其他MongoDB实例的传出连接的统计数据。Yes支持
connectionStatusReports the authentication state for the current connection.报告当前连接的身份验证状态。Yes支持
dataSizeReturns the data size for a range of data. For internal use.返回数据范围的数据大小。供内部使用。No support for M0 and Flex clusters.不支持M0和Flex集群
dbHashReturns hash value a database and its collections返回数据库及其集合的哈希值.No support for M0 and Flex clusters.不支持M0和Flex集群
dbStatsReports storage utilization statistics for the specified database.报告指定数据库的存储利用率统计信息。Limited support for M0 and Flex clusters.M0和Flex集群的支持有限。
explainReturns information on the execution of various operations.返回有关各种操作执行的信息。Yes支持
getCmdLineOptsReturns a document with the run-time arguments to the MongoDB instance and their parsed options.向MongoDB实例返回一个包含运行时参数及其解析选项的文档。Yes支持
getLogReturns recent log messages.返回最近的日志消息。Yes支持
hostInfoReturns data that reflects the underlying host system.返回反映底层主机系统的数据。No support for M0 and Flex clusters.不支持M0和Flex集群
listCommandsLists all database commands provided by the current mongod instance.列出当前mongod实例提供的所有数据库命令。Yes支持
lockInfoInternal command that returns information on locks that are currently being held or pending. Only available for mongod instances.返回当前持有或挂起的锁信息的内部命令。仅适用于mongod实例。No support for M0 and Flex clusters.不支持M0和Flex集群
pingInternal command that tests intra-deployment connectivity.测试内部部署连接的内部命令。Yes支持
profileInterface for the database profiler.数据库分析器的接口。Yes支持
serverStatusReturns a collection metrics on instance-wide resource utilization and status.返回实例范围内资源利用率和状态的集合指标。Yes支持
shardConnPoolStatsRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Use connPoolStats instead.请改用connPoolStatsYes支持
topReturns raw usage statistics for each database in the mongod instance.返回mongod实例中每个数据库的原始使用统计数据。Yes支持
validateInternal command that scans for a collection's data and indexes for correctness.扫描集合的数据和索引是否正确的内部命令。No support for M0 and Flex clusters.不支持M0和Flex集群
whatsmyuriInternal command that returns information on the current client.返回当前客户端信息的内部命令。Yes支持

Auditing Commands审核命令

Name名称Description描述MongoDB Atlas SupportMongoDB Atlas 支持
getAuditConfigDeprecated in version 7.1:7.1版本中已弃用: Use the auditConfig cluster parameter instead.请改用auditConfig群集参数。
Retrieves audit configurations from mongod and mongos instances.mongodmongos实例中检索审计配置。
No
logApplicationMessagePosts a custom message to the audit log.将自定义消息发布到审核日志中。Yes支持
setAuditConfigDeprecated in version 7.1:7.1版本中已弃用: Use the auditConfig cluster parameter instead.请改用auditConfig群集参数。
Sets audit configurations for mongod and mongos instances at runtime.在运行时为mongodmongos实例设置审计配置。
No

MongoDB Search CommandsMongoDB搜索命令

New in version 7.07.0版本新增: (Also available starting in 6.0.7从6.0.7开始也可用)

Name名称Description描述
createSearchIndexesCreates one or more MongoDB Search indexes on a specified collection or view.在指定的集合或视图上创建一个或多个MongoDB搜索索引
dropSearchIndexDeletes an existing MongoDB Search index.删除现有的MongoDB搜索索引
updateSearchIndexUpdates an existing MongoDB Search index.更新现有的MongoDB搜索索引