Database Commands数据库命令

On this page本页内容

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 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(). 运行数据库命令时,将该命令指定为db.runCommand()的文档。The document's key is the command to run, and the value is typically supplied as 1. 文档的键是要运行的命令,值通常为1The value does not affect the output of the command for example:该值不影响命令的输出,例如:

db.runCommand( { hello: 1 } )

User Commands用户命令

Aggregation Commands聚合命令

Name名称Description描述
aggregatePerforms aggregation tasks such as $group using an aggregation pipeline.使用聚合管道执行聚合任务,如$group
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.对大型数据集执行map-reduce聚合。

Geospatial Commands地理空间命令

Name名称Description描述
geoSearchRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Performs a geospatial query that uses MongoDB's haystack index functionality.使用MongoDB的haystack索引功能执行地理空间查询。

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

Name名称Description描述
deleteDeletes one or more documents.删除一个或多个文档。
findSelects documents in a collection or a view.选择集合或视图中的文档。
findAndModifyReturns and modifies a single document.返回和修改单个文档。
getMoreReturns batches of documents currently pointed to by the cursor.返回游标当前指向的成批文档。
insertInserts one or more documents.插入一个或多个文档。
resetErrorRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Resets the last error status.重置最后一个错误状态。
updateUpdates one or more documents.更新一个或多个文档。

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

Name名称Description描述
planCacheClearRemoves cached query plan(s) for a collection.删除集合的缓存查询计划。
planCacheClearFiltersClears index filter(s) for a collection.清除集合的索引筛选器。
planCacheListFiltersLists the index filters for a collection.列出集合的索引筛选器。
planCacheSetFilterSets an index filter for a collection.设置集合的索引筛选器。

Database Operations数据库操作

Authentication Commands身份验证命令

Name名称Description描述
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用户管理命令

Name名称Description描述
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角色管理命令

Name名称Description描述
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复制命令

Name名称Description描述
applyOpsInternal command that applies oplog entries to the current data set.oplog条目应用于当前数据集的内部命令。
helloDisplays information about this member's role in the replica set, including whether it is the primary.显示有关此成员在副本集中的角色的信息,包括它是否为主成员。
replSetAbortPrimaryCatchUpForces the elected primary to abort sync (catch up) then complete the transition to primary.强制选定的primary中止同步(追赶),然后完成到主设备的转换。
replSetFreezePrevents the current member from seeking election as primary for a period of time.阻止当前成员在一段时间内寻求作为primary的选举。
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.启用或禁用维护模式,使secondary节点处于RECOVERING状态。
replSetReconfigApplies a new configuration to an existing replica set.将新配置应用于现有副本集。
replSetResizeOplogDynamically resizes the oplog for a replica set member. 动态调整副本集成员的oplog大小。Available for WiredTiger storage engine only.仅适用于WiredTiger存储引擎。
replSetStepDownForces the current primary to step down and become a secondary, forcing an election.迫使目前的primary下台,成为secondary,强制选举。
replSetSyncFromExplicitly override the default logic for selecting a member to replicate from.显式重写用于选择要从中复制的成员的默认逻辑。
Tip提示
See also: 参阅:

Replication for more information regarding replication.副本以获取有关副本的更多信息。

Sharding Commands分片命令

Name名称Description描述
abortReshardCollection

Aborts a resharding operation.中止重新分片操作

New in version 5.0.在版本5.0中新增

addShardAdds a shard to a sharded cluster.将分片添加到分片群集
addShardToZoneAssociates 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.在版本4.4中新增

balancerStartStarts a balancer thread.启动一个均衡器线程。
balancerStatusReturns information on the balancer status.返回有关均衡器状态的信息。
balancerStopStops the balancer thread.停止均衡器线程。
checkShardingIndexInternal command that validates index on shard key.验证分片键索引的内部命令。
clearJumboFlagClears the jumbo flag for a chunk.清除块的jumbo标志。
cleanupOrphanedRemoves 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.在版本5.0中新增

commitReshardCollection

Forces a resharding operation to block writes and complete.强制重新分片操作阻止写入并完成。

New in version 5.0.在版本5.0中新增

enableShardingEnables sharding on a specific database.特定的数据库支持分片。
flushRouterConfigForces a mongod/mongos instance to update its cached routing metadata.强制mongod/mongos实例更新其缓存的路由元数据。
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.验证进程是否为mongos
listShardsReturns a list of configured shards.返回已配置分片的列表。
medianKeyDeprecated internal command. 不推荐使用内部命令。See splitVector.请参阅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.提供在单个分片上组合块的功能。
refineCollectionShardKey

Refines a collection's shard key by adding a suffix to the existing key.通过向现有密钥添加后缀来细化集合的分片密钥。

New in version 4.4.在版本4.4中新增

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.支持在分片集群中配置区域。
reshardCollection

Initiates a resharding operation to change the shard key for a collection, changing the distribution of your data.启动重新分片操作以更改集合的分片密钥,从而更改数据的分发。

New in version 5.0.在版本5.0中新增

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.报告mongod是否为分片群集的成员。
splitCreates a new chunk.创建新块
splitVectorInternal command that determines split points.确定拆分点的内部命令。
unsetShardingRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Internal command that affects connections between instances in a MongoDB deployment.影响MongoDB部署中实例之间连接的内部命令。
updateZoneKeyRangeAdds or removes the association between a range of sharded data and a zone. 添加或删除一系列分片数据与分区之间的关联。Supports configuring zones in sharded clusters.支持在分片集群中配置区域
Tip提示
See also: 参阅:

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

Session Commands会话命令

Command命令Description描述
abortTransaction

Abort transaction.中止事务。

New in version 4.0.在版本4.0中新增

commitTransaction

Commit transaction.提交事务。

New in version 4.0.在版本4.0中新增

endSessionsExpire sessions before the sessions' timeout period.在会话超时之前使会话过期。
killAllSessionsKill all sessions.终止所有会话。
killAllSessionsByPatternKill all sessions that match the specified pattern终止与指定模式匹配的所有会话
killSessionsKill specified sessions.杀死指定的会话。
refreshSessionsRefresh idle sessions.刷新空闲会话。
startSessionStarts a new session.开始新的会话。

Administration Commands管理命令

Name名称Description描述
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.返回使用GridFS存储的文件的md5哈希。
fsyncFlushes pending writes to the storage layer and locks the database to allow backups.刷新对存储层的挂起写入,并锁定数据库以允许备份。
fsyncUnlockUnlocks one fsync lock.解锁一个fsync锁。
getDefaultRWConcern

Retrieves the global default read and write concern options for the deployment.检索部署的全局默认读写关注点选项。

New in version 4.4.在版本4.4中新增

getParameterRetrieves configuration options.检索配置选项。
killCursorsKills the specified cursors for a collection.终止集合的指定游标。
killOpTerminates an operation as specified by the operation ID.终止操作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.旋转MongoDB日志以防止单个文件占用太多空间。
reIndexRebuilds all indexes on a collection.重建集合上的所有索引。
renameCollectionChanges the name of an existing collection.更改现有集合的名称。
rotateCertificatesPerforms online TLS certificate rotation.执行在线TLS证书轮换。
setFeatureCompatibilityVersionEnables or disables features that persist data that are backwards-incompatible.启用或禁用保留向后不兼容数据的功能。
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.更改在主索引将这些索引标记为就绪之前,必须投票提交正在进行的索引生成的最小数据承载成员数(即提交仲裁),包括主成员。
setParameterModifies configuration options.修改配置选项。
setDefaultRWConcern

Sets the global default read and write concern options for the deployment.设置部署的全局默认读写关注点选项。

New in version 4.4.在版本4.4中新增

shutdownShuts down the mongod or mongos process.关闭mongodmongos进程。

Diagnostic Commands诊断命令

Name名称Description描述
buildInfoDisplays statistics about the MongoDB build.显示有关MongoDB构建的统计信息。
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.报告从该MongoDB实例到部署中其他MongoDB实例的传出连接的统计信息。
connectionStatusReports the authentication state for the current connection.报告当前连接的身份验证状态。
cursorInfoRemoved in MongoDB 3.2. Replaced with metrics.cursor.在MongoDB 3.2中删除。替换为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.报告指定数据库的存储利用率统计信息。
driverOIDTestInternal command that converts an ObjectId to a string to support tests.将ObjectId转换为字符串以支持测试的内部命令。
explainReturns information on the execution of various operations.返回有关执行各种操作的信息。
featuresReports on features available in the current MongoDB instance.报告当前MongoDB实例中可用的功能。
getCmdLineOptsReturns a document with the run-time arguments to the MongoDB instance and their parsed options.将包含运行时参数的文档返回给MongoDB实例及其解析的选项。
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.列出当前mongod实例提供的所有数据库命令。
lockInfoInternal command that returns information on locks that are currently being held or pending. 内部命令,该命令返回有关当前被保留或挂起的锁的信息。Only available for mongod instances.仅适用于mongod实例。
netstatInternal command that reports on intra-deployment connectivity. 报告内部部署连接的内部命令。Only available for mongos instances.仅适用于mongos实例。
pingInternal command that tests intra-deployment connectivity.测试部署内连接的内部命令。
profileInterface for the database profiler.数据库探查器的接口。
serverStatusReturns a collection metrics on instance-wide resource utilization and status.返回实例范围内资源利用率和状态的集合度量。
shardConnPoolStatsRemoved in MongoDB 5.0.在MongoDB 5.0中删除。 Use connPoolStats instead.使用connPoolStats代替。
topReturns raw usage statistics for each database in the mongod instance.返回mongod实例中每个数据库的原始使用统计信息。
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免费监控命令

Name名称Description描述
setFreeMonitoringEnables/disables free monitoring during runtime.在运行时启用/禁用免费监视。

Auditing Commands审核命令

Name名称Description描述
logApplicationMessagePosts a custom message to the audit log.将自定义消息发布到审核日志。
←  $zip (aggregation)Aggregation Commands →