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 mongo shell helpers.一些命令文档还包括相关的mongo shell助手。

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.有关特定命令的详细信息,包括语法和示例,请单击特定命令以转到其参考页面。

User Commands用户命令

Aggregation Commands聚合命令

Name名称Description描述
aggregate Performs aggregation tasks such as group using the aggregation framework.使用聚合框架执行聚合任务,例如分组。
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.对大型数据集执行map-reduce聚合。

Geospatial Commands地理空间命令

Name名称Description描述
geoSearch Performs a geospatial query that uses MongoDB’s haystack index functionality.使用MongoDB的haystack索引功能执行地理空间查询。

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.返回和修改单个文档。
getLastError Returns the success status of the last operation.返回上次操作的成功状态。
getMore Returns batches of documents currently pointed to by the cursor.返回游标当前指向的成批文档。
insert Inserts one or more documents.插入一个或多个文档。
resetError Deprecated. 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.oplog条目应用于当前数据集的内部命令。
isMaster Displays information about this member’s role in the replica set, including whether it is the master.显示有关此成员在副本集中的角色的信息,包括该成员是否为主成员。
replSetAbortPrimaryCatchUp Forces the elected primary to abort sync (catch up) then complete the transition to primary.强制选定的primary中止同步(追赶),然后完成到primary的转换。
replSetFreeze Prevents the current member from seeking election as primary for a period of time.阻止当前成员在一段时间内寻求作为primary的选举。
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.启用或禁用维护模式,使secondary节点处于RECOVERING(恢复)状态。
replSetReconfig Applies a new configuration to an existing replica set.将新配置应用于现有副本集。
replSetResizeOplog Dynamically resizes the oplog for a replica set member. 动态调整副本集成员的oplog大小。Available for WiredTiger storage engine only.仅适用于WiredTiger存储引擎。
replSetStepDown Forces the current primary to step down and become a secondary, forcing an election.迫使目前的primary下台,成为secondary,迫使选举。
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描述
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.版本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.清除块的jumbo标志。
cleanupOrphaned Removes orphaned data with shard key values outside of the ranges of the chunks owned by a shard.移除碎片键值超出碎片拥有的区块范围的孤立数据。
enableSharding Enables sharding on a specific database.在特定数据库上启用分片。
flushRouterConfig Forces a mongod/mongos instance to update its cached routing metadata.强制mongod/mongos实例更新其缓存的路由元数据。
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.验证进程是否为mongos
listShards Returns a list of configured shards.返回已配置碎片的列表。
medianKey Deprecated internal command. 不推荐使用内部命令。See splitVector.请参阅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.版本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.支持在分片集群中配置区域
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.报告mongod是否为分片群集的成员。
split Creates a new chunk.创建一个新
splitChunk Internal command to split chunk. 分割区块的内部命令。Instead use the methods sh.splitFind() and sh.splitAt().而是使用sh.splitFind()方法和sh.splitAt()方法。
splitVector Internal command that determines split points.确定拆分点的内部命令。
unsetSharding Deprecated. 不赞成Internal command that affects connections between instances in a MongoDB deployment.影响MongoDB部署中实例之间连接的内部命令。
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.分片以了解有关MongoDB切分功能的更多信息。

Session Commands会话命令

Commands命令Descriptions描述
abortTransaction

Abort transaction.中止交易。

New in version 4.0.版本4.0中的新功能。

commitTransaction

Commit transaction.提交事务。

New in version 4.0.版本4.0中的新功能。

endSessions

Expire sessions before the sessions’ timeout period.在会话超时之前使会话过期。

New in version 3.6.版本3.6中的新功能。

killAllSessions

Kill all sessions.终止所有会话。

New in version 3.6.版本3.6中的新功能。

killAllSessionsByPattern

Kill all sessions that match the specified pattern终止与指定模式匹配的所有会话

New in version 3.6.版本3.6中的新功能。

killSessions

Kill specified sessions.杀死指定的会话。

New in version 3.6.版本3.6中的新功能。

refreshSessions

Refresh idle sessions.刷新空闲会话。

New in version 3.6.版本3.6中的新功能。

startSession

Starts a new session.开始新的会话。

New in version 3.6.版本3.6中的新功能。

Administration Commands管理命令

Name名称Description描述
cloneCollectionAsCapped Copies a non-capped collection as a new capped collection.将非封顶集合复制为新的封顶集合
collMod Add options to a collection or modify a view definition.向集合添加选项或修改视图定义。
compact Defragments a collection and rebuilds the indexes.对集合进行碎片整理并重建索引。
connPoolSync Internal command to flush connection pool.刷新连接池的内部命令。
convertToCapped Converts a non-capped collection to a capped collection.将非封顶集合转换为封顶集合。
create Creates a collection or a view.创建集合或视图。
createIndexes Builds one or more indexes for a collection.为集合生成一个或多个索引。
currentOp Returns a document that contains information on in-progress operations for the database instance.返回一个文档,其中包含有关数据库实例正在进行的操作的信息。
drop Removes the specified collection from the database.从数据库中删除指定的集合。
dropDatabase Removes the current database.删除当前数据库。
dropConnections Drops outgoing connections to the specified list of hosts.将传出连接断开到指定的主机列表。
dropIndexes Removes indexes from a collection.从集合中删除索引。
filemd5 Returns the md5 hash for files stored using GridFS.返回使用GridFS存储的文件的md5哈希。
fsync Flushes pending writes to the storage layer and locks the database to allow backups.刷新对存储层的挂起写入,并锁定数据库以允许备份。
fsyncUnlock Unlocks one fsync lock.解锁一个fsync锁。
getDefaultRWConcern

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

New in version 4.4.版本4.4中的新功能。

getParameter Retrieves configuration options.检索配置选项。
killCursors Kills the specified cursors for a collection.终止集合的指定游标。
killOp Terminates an operation as specified by the operation ID.终止操作ID指定的操作。
listCollections Returns a list of collections in the current database.返回当前数据库中集合的列表。
listDatabases Returns a document that lists all databases and returns basic database statistics.返回列出所有数据库并返回基本数据库统计信息的文档。
listIndexes Lists all indexes for a collection.列出集合的所有索引。
logRotate Rotates the MongoDB logs to prevent a single file from taking too much space.旋转MongoDB日志以防止单个文件占用太多空间。
reIndex Rebuilds all indexes on a collection.重建集合上的所有索引。
renameCollection Changes the name of an existing collection.更改现有集合的名称。
setFeatureCompatibilityVersion Enables or disables features that persist data that are backwards-incompatible.启用或禁用保留向后不兼容数据的功能。
setIndexCommitQuorum Changes 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.更改包含数据的成员(即commit quorum)的最小数量,包括主成员,在主成员将索引标记为就绪之前,必须投票提交正在进行的索引生成
setParameter Modifies configuration options.修改配置选项。
setDefaultRWConcern

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

New in version 4.4.版本4.4中的新功能。

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

Diagnostic Commands诊断命令

Name名称Description描述
availableQueryOptions Internal command that reports on the capabilities of the current MongoDB instance.报告当前MongoDB实例功能的内部命令。
buildInfo Displays statistics about the MongoDB build.显示有关MongoDB构建的统计信息。
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.报告从该MongoDB实例到部署中其他MongoDB实例的传出连接的统计信息。
connectionStatus Reports the authentication state for the current connection.报告当前连接的身份验证状态。
cursorInfo Removed in MongoDB 3.2. 在MongoDB 3.2中删除。Replaced with metrics.cursor.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.将ObjectId转换为字符串以支持测试的内部命令。
explain Returns information on the execution of various operations.返回有关执行各种操作的信息。
features Reports on features available in the current MongoDB instance.报告当前MongoDB实例中可用的功能。
getCmdLineOpts Returns a document with the run-time arguments to the MongoDB instance and their parsed options.将包含运行时参数的文档返回给MongoDB实例及其解析的选项。
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.列出当前mongod实例提供的所有数据库命令。
lockInfo Internal command that returns information on locks that are currently being held or pending. 内部命令,该命令返回有关当前被保留或挂起的锁的信息。Only available for mongod instances.仅适用于mongod实例。
netstat Internal command that reports on intra-deployment connectivity. 报告内部部署连接的内部命令。Only available for mongos instances.仅适用于mongos实例。
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

Deprecated in 4.4 Use :dbcommand:`connPoolStats` instead.在4.4中不推荐使用,请改用dbcommandconnPoolStats

Reports statistics on a mongos’s connection pool for client operations against shards.报告mongos连接池的统计数据,以便针对碎片执行客户端操作。

top Returns raw usage statistics for each database in the mongod instance.返回mongod实例中每个数据库的原始使用统计信息。
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.将自定义消息发布到审核日志。