Docs HomeMongoDB Shell

Methods方法

The following document lists the available methods in the MongoDB Shell. 以下文档列出了MongoDB Shell中可用的方法。Click a method to see its documentation in the MongoDB Manual, including syntax and examples.单击一个方法可以在MongoDB手册中查看其文档,包括语法和示例。

Important

Methods which reset the shell's connection to the server trigger a termination of all open server sessions. 重置shell与服务器的连接的方法会触发所有打开的服务器会话的终止。When a session ends, all in-progress operations are terminated as well, and the client must re-authenticate if authentication is enabled.会话结束时,所有正在进行的操作也将终止,如果启用了身份验证,则客户端必须重新进行身份验证。

The following methods reset the shell's connection:以下方法重置外壳的连接:

  • db.auth
  • Mongo.setReadPref
  • Mongo.setReadConcern

Administration Methods管理方法

Method方法Description描述
db.adminCommand()Runs a command against the admin database.admin数据库运行命令。
db.currentOp()Reports the current in-progress operations.报告当前正在进行的操作。
db.killOp()Terminates a specified operation.终止指定的操作。
db.shutdownServer()Shuts down the current mongod or mongos process cleanly and safely.干净安全地关闭当前mongodmongos进程。
db.fsyncLock()Flushes writes to disk and locks the database to prevent write operations and assist backup operations.刷新对磁盘的写入并锁定数据库,以防止写入操作并协助备份操作。
db.fsyncUnlock()Allows writes to continue on a database locked with db.fsyncLock().允许在使用db.fsyncLock()锁定的数据库上继续写入。

Atlas Search Index MethodsAtlas搜索索引方法

Atlas Search indexes let you query data in Atlas Search. Atlas Search索引允许您在Atlas Search中查询数据。Atlas Search indexes enable performant text search queries by mapping search terms to the documents that contain those terms.Atlas Search索引通过将搜索术语映射到包含这些术语的文档来实现高性能文本搜索查询。

Use the following methods to manage Atlas Search indexes.使用以下方法管理Atlas Search索引。

Important

The following methods can only be run on deployments hosted on MongoDB Atlas.以下方法只能在MongoDB Atlas上托管的部署上运行。

Name名称Description描述
db.collection.createSearchIndex()Creates one or more Atlas Search indexes on a specified collection.在指定集合上创建一个或多个Atlas Search索引。
db.collection.dropSearchIndex()Deletes an existing Atlas Search index.删除现有的Atlas Search索引。
db.collection.getSearchIndexes()Returns information about existing Atlas Search indexes on a specified collection.返回有关指定集合上现有Atlas Search索引的信息。
db.collection.updateSearchIndex()Updates an existing Atlas Search index.更新现有的Atlas Search索引。

Bulk Operation Methods批量操作方法

Method方法Description描述
db.collection.initializeOrderedBulkOp()Initializes and returns a new Bulk() operations builder for a collection. 初始化并返回集合的新Bulk()操作生成器。The builder constructs an ordered list of write operations that MongoDB executes in bulk.构建器构建了MongoDB批量执行的写入操作的有序列表。
db.collection.initializeUnorderedBulkOp()Initializes and returns a new Bulk() operations builder for a collection. 初始化并返回集合的新Bulk()操作生成器。The builder constructs an unordered list of write operations that MongoDB executes in bulk.构建器构建了MongoDB批量执行的写入操作的无序列表。
Bulk()Creates a bulk operations builder used to construct a list of write operations to perform in bulk for a single collection. 创建一个大容量操作生成器,用于构造要对单个集合进行大容量执行的写入操作的列表。To instantiate the builder, use either the db.collection.initializeOrderedBulkOp() or the db.collection.initializeUnorderedBulkOp() method.要实例化生成器,请使用db.collection.initializeOrderedBulkOp()db.collection.initializeUnorderedBulkOp()方法。
Bulk.execute()Executes the list of operations built by the Bulk() operations builder.执行Bulk()操作生成器生成的操作列表。
Bulk.find()Specifies a query condition for an update or a remove operation.指定更新或删除操作的查询条件。
Bulk.find.hint()Sets the hint option that specifies the index to support the bulk operation.设置用于指定支持批量操作的索引的提示选项。
Bulk.find.remove()Adds a remove operation to a bulk operations list.将删除操作添加到大容量操作列表中。
Bulk.find.removeOne()Adds a single document remove operation to a bulk operations list.将单个文档删除操作添加到批量操作列表中。
Bulk.find.replaceOne()Adds a single document replacement operation to a bulk operations list.将单个文档替换操作添加到批量操作列表中。
Bulk.find.updateOne()Adds a single document update operation to a bulk operations list.将单个文档更新操作添加到批量操作列表中。
Bulk.find.update()Adds a multi update operation to a bulk operations list. multi更新操作添加到批量操作列表中。The method updates specific fields in existing documents.该方法更新现有文档中的特定字段。
Bulk.find.upsert()Sets the upsert option to true for an update or a replacement operation.将更新或替换操作的upsert选项设置为true
Bulk.getOperations()Returns an array of write operations executed through Bulk.execute().返回通过Bulk.execute()执行的写入操作的数组。
Bulk.insert()Adds an insert operation to a bulk operations list.将插入操作添加到批量操作列表中。
Bulk.toJSON()Returns a JSON document that contains the number of operations and batches in the Bulk() object.返回一个JSON文档,该文档包含Bulk()对象中的操作数和批处理数。
Bulk.toString()Returns as a string a JSON document that contains the number of operations and batches in the Bulk() object.以字符串形式返回一个JSON文档,该文档包含Bulk()对象中的操作数和批处理数。

Collection Methods集合方法

Method方法Description描述
db.collection.aggregate()Provides access to the aggregation pipeline.提供对聚合管道的访问。
db.collection.bulkWrite()Provides bulk write operation functionality.提供大容量写入操作功能。
db.collection.count()Deprecated in mongosh 1.0.6. mongosh 1.0.6中已弃用。Use db.collection.countDocuments() or db.collection.estimatedDocumentCount() instead.请改用db.collection.countDocuments()db.collection.estimatedDocumentCount()
db.collection.countDocuments()Returns a count of the number of documents in a collection or a view. 返回集合或视图中文档数的计数。Wraps the $group aggregation stage with a $sum expression.$sum表达式包装$group聚合阶段。
db.collection.estimatedDocumentCount()Returns an approximate count of the documents in a collection or a view.返回集合或视图中文档的近似计数。
db.collection.createIndex()Builds an index on a collection.对集合生成索引。
db.collection.createIndexes()Builds one or more indexes on a collection.在集合上生成一个或多个索引。
db.collection.dataSize()Returns the size of the collection. 返回集合的大小。Wraps the size field in the output of the collStats.包装collStats输出中的size字段。
db.collection.deleteOne()Deletes a single document in a collection.删除集合中的单个文档。
db.collection.deleteMany()Deletes multiple documents in a collection.删除集合中的多个文档。
db.collection.distinct()Returns an array of documents that have distinct values for the specified field.返回指定字段具有不同值的文档数组。
db.collection.drop()Removes the specified collection from the database.从数据库中删除指定的集合。
db.collection.dropIndex()Removes a specified index on a collection.删除集合上的指定索引。
db.collection.dropIndexes()Removes all indexes on a collection.删除集合上的所有索引。
db.collection.ensureIndex()Deprecated. 已弃用。Use db.collection.createIndex().使用db.collection.createIndex()
db.collection.explain()Returns information on the query execution of various methods.返回有关各种方法的查询执行的信息。
db.collection.find()Performs a query on a collection or a view and returns a cursor object.对集合或视图执行查询并返回游标对象。
db.collection.findAndModify()Atomically modifies and returns a single document.原子化地修改并返回单个文档。
db.collection.findOne()Performs a query and returns a single document.执行查询并返回单个文档。
db.collection.findOneAndDelete()Finds a single document and deletes it.查找单个文档并将其删除。
db.collection.findOneAndReplace()Finds a single document and replaces it.查找单个文档并替换它。
db.collection.findOneAndUpdate()Finds a single document and updates it.查找单个文档并更新它。
db.collection.getIndexes()Returns an array of documents that describe the existing indexes on a collection.返回描述集合上现有索引的文档数组。
db.collection.getShardDistribution()Prints the data distribution statistics for a sharded collection.打印分片集合的数据分布统计信息。
db.collection.getShardVersion()Provides a wrapper for the database command getShardVersion.为数据库命令getShardVersion提供包装器。
db.collection.insertOne()Inserts a new document in a collection.在集合中插入新文档。
db.collection.insertMany()Inserts several new document in a collection.在集合中插入几个新文档。
db.collection.isCapped()Reports if a collection is a capped collection.报告集合是否为封顶集合
db.collection.mapReduce()Runs map-reduce aggregation operations on a collection.对集合运行map-reduce聚合操作。
db.collection.reIndex()Rebuilds all existing indexes on a collection.重新生成集合上的所有现有索引。
db.collection.renameCollection()Changes the name of a collection.更改集合的名称。
db.collection.replaceOne()Replaces a single document in a collection.替换集合中的单个文档。
db.collection.stats()Reports on the state of a collection. 报告集合的状态。Provides a wrapper around the collStats.提供collStats的包装。
db.collection.storageSize()Reports the total size used by the collection in bytes. 报告集合使用的总大小(以字节为单位)。Provides a wrapper around the storageSize field of the collStats output.提供collStats输出的storageSize字段的包装。
db.collection.totalIndexSize()Reports the total size used by the indexes on a collection. 报告集合上索引使用的总大小。Provides a wrapper around the totalIndexSize field of the collStats output.collStats输出的totalIndexSize字段提供包装。
db.collection.totalSize()Reports the total size of a collection, including the size of all documents and all indexes on a collection.报告集合的总大小,包括集合上所有文档和所有索引的大小。
db.collection.updateOne()Modifies a single document in a collection.修改集合中的单个文档。
db.collection.updateMany()Modifies multiple documents in a collection.修改集合中的多个文档。
db.collection.validate()Validates a collection.验证集合。
db.collection.watch()Opens a change stream cursor on the collection.在集合上打开更改流游标。

Connection Methods连接方法

Method方法Description描述
Mongo()JavaScript constructor to instantiate a database connection from the mongo shell or from a JavaScript file.JavaScript构造函数,用于从mongo shell或JavaScript文件实例化数据库连接。
The Mongo() method has the following parameters:Mongo()方法具有以下参数:
Parameter参数Type类型Description描述
hoststringOptional可选
The connection string for the target database connection.目标数据库连接的连接字符串。
If omitted, Mongo() instantiates a connection to the localhost interface on the default port 27017.如果省略,Mongo()将实例化到默认端口27017上的localhost接口的连接。
autoEncryptionOptsDocumentOptional可选


New in version 4.2.4.2版新增。
Configuration parameters for enabling Client-Side Field Level Encryption.用于启用客户端字段级加密的配置参数。
autoEncryptionOpts overrides the existing client-side field level encryption configuration of the database connection. 覆盖数据库连接的现有客户端字段级加密配置。If omitted, Mongo() inherits the client-side field level encryption configuration of the current database connection.如果省略,Mongo()将继承当前数据库连接的客户端字段级加密配置。
For documentation of usage and syntax, see AutoEncryptionOpts.有关用法和语法的文档,请参阅AutoEncryptionOpts
Mongo.getDB()Returns a database object.返回数据库对象。
Mongo.setReadPref()Sets the read preference for the MongoDB connection.设置MongoDB连接的读取首选项
Mongo.watch()Opens a change stream cursor for a replica set or a sharded cluster to report on all its non-system collections across its databases, with the exception of the admin, local, and config databases.打开副本集或分片集群的更改流游标,以报告其数据库中的所有非系统集合(admin数据库、local数据库和config数据库除外)。

Cursor Methods游标方法

Method方法Description描述
cursor.addOption()Adds special wire protocol flags that modify the behavior of the query.添加用于修改查询行为的特殊连线协议标志。
cursor.allowPartialResults()Allows db.collection.find() operations against a sharded collection to return partial results, rather than an error, if one or more queried shards are unavailable.如果一个或多个查询的分片不可用,则允许对分片集合执行db.collection.find()操作以返回部分结果,而不是错误。
cursor.batchSize()Controls the number of documents MongoDB will return to the client in a single network message.控制MongoDB在单个网络消息中返回给客户端的文档数量。
The following example query returns results in batches of 100:以下示例查询以100为一批返回结果:
db.myCollection.find().batchSize(100)
cursor.close()Close a cursor and free associated server resources.关闭游标并释放关联的服务器资源。
cursor.collation()Specifies the collation for the cursor returned by the db.collection.find().指定db.collection.find()返回的游标的排序规则。
cursor.comment()Attaches a comment to the query to allow for traceability in the logs and the system.profile collection.将注释附加到查询,以允许在日志和system.profile集合中进行跟踪。
cursor.count()Modifies the cursor to return the number of documents in the result set rather than the documents themselves.修改游标以返回结果集中的文档数,而不是文档本身。
cursor.explain()Reports on the query execution plan for a cursor.报告游标的查询执行计划。
cursor.forEach()Applies a JavaScript function for every document in a cursor.为游标中的每个文档应用JavaScript函数。
cursor.hasNext()Returns true if the cursor has documents and can be iterated.如果游标包含文档并且可以迭代,则返回true
cursor.hint()Forces MongoDB to use a specific index for a query.强制MongoDB为查询使用特定的索引。
cursor.isClosed()Returns true if the cursor is closed.如果游标关闭,则返回true
cursor.isExhausted()Returns true if the cursor is closed and there are no objects remaining in the batch.如果游标已关闭并且批处理中没有剩余对象,则返回true
cursor.itcount()Computes the total number of documents in the cursor client-side by fetching and iterating the result set.通过获取和迭代结果集来计算游标客户端中的文档总数。
cursor.limit()Constrains the size of a cursor's result set.约束游标的结果集的大小。
cursor.map()Applies a function to each document in a cursor and collects the return values in an array.将函数应用于游标中的每个文档,并集合数组中的返回值。
cursor.max()Specifies an exclusive upper index bound for a cursor. 指定游标的独占索引上限。For use with cursor.hint()用于与cursor.hint()配合使用
cursor.maxTimeMS()Specifies a cumulative time limit in milliseconds for processing operations on a cursor.指定处理游标上的操作的累积时间限制(以毫秒为单位)。
cursor.min()Specifies an inclusive lower index bound for a cursor. 为游标指定包含索引的下限。For use with cursor.hint()用于与cursor.hint()配合使用
cursor.next()Returns the next document in a cursor.返回游标中的下一个文档。
cursor.noCursorTimeout()Instructs the server to avoid closing a cursor automatically after a period of inactivity.指示服务器避免在一段时间不活动后自动关闭游标。
cursor.objsLeftInBatch()Returns the number of documents left in the current cursor batch.返回当前游标批处理中剩余的文档数。
cursor.readConcern()Specifies a read concern for a db.collection.find() operation.指定db.collection.find()操作的读取关注点
cursor.readPref()Specifies a read preference to a cursor to control how the client directs queries to a replica set.指定游标的读取首选项,以控制客户端如何将查询定向到副本集
cursor.returnKey()Modifies the cursor to return index keys rather than the documents.修改游标以返回索引键而不是文档。
cursor.showRecordId()Adds an internal storage engine ID field to each document returned by the cursor.向游标返回的每个文档添加一个内部存储引擎ID字段。
cursor.size()Returns a count of the documents in the cursor after applying skip() and limit() methods.返回应用skip()limit()方法后游标中文档的计数。
cursor.skip()Returns a cursor that begins returning results only after passing or skipping a number of documents.返回一个游标,该游标仅在传递或跳过多个文档后才开始返回结果。
cursor.sort()Returns results ordered according to a sort specification.返回根据排序规范排序的结果。
cursor.tailable()Marks the cursor as tailable. Only valid for cursors over capped collections.将游标标记为可裁剪。仅对超过上限集合的游标有效。
cursor.toArray()Returns an array that contains all documents returned by the cursor.返回一个数组,该数组包含游标返回的所有文档。

Database Methods数据库方法

Method方法Description描述
db.aggregate()Runs admin/diagnostic pipeline which does not require an underlying collection.运行不需要基础集合的管理/诊断管道。
db.createCollection()Creates a new collection or view.创建新的集合或视图。
db.createView()Creates a view as the result of applying the specified aggregation pipeline to the source collection or view.将指定的聚合管道应用于源集合或视图,从而创建视图。
db.commandHelp()Displays help text for the specified database command.显示指定数据库命令的帮助文本。
db.dropDatabase()Removes the current database.删除当前数据库。
db.getCollection()Returns a collection or view object. Used to access collections with names that are not valid in the mongo shell.返回集合或视图对象。用于访问名称在mongo shell中无效的集合。
db.getCollectionInfos()Returns collection information for all collections and views in the current database.返回当前数据库中所有集合和视图的集合信息。
db.getCollectionNames()Lists all collections and views in the current database.列出当前数据库中的所有集合和视图。
db.getMongo()Returns the current database connection.返回当前数据库连接。
db.getLogComponents()Returns the current log verbosity settings.返回当前日志详细信息设置。
db.getName()Returns the name of the current database.返回当前数据库的名称。
db.getProfilingStatus()Returns the current profile level, slowOpThresholdMs setting, and slowOpSampleRate setting.返回当前探查器级别slowOpThresholdMs设置和slowOpSampleRate设置。
db.getSiblingDB()Provides access to the specified database.提供对指定数据库的访问权限。
db.listCommands()Provides a list of all database commands.提供所有数据库命令的列表。
db.logout()Ends an authenticated session.结束经过身份验证的会话。
db.printShardingStatus()Prints a formatted report of the sharding configuration and the information regarding existing chunks in a sharded cluster.打印分片配置的格式化报告以及关于分片集群中现有块的信息。
db.runCommand()Runs a database command.运行数据库命令
db.setLogLevel()Sets a single verbosity level for log messages.日志消息设置单个详细级别。
db.setProfilingLevel()Configures the database profiler level, slowms, and sampleRate.配置数据库探查器级别slowmssampleRate
db.watch()Opens a change stream cursor for a database to report on all its non-system collections.打开数据库的更改流游标以报告其所有非系统集合。

Free Monitoring Methods免费监控方法

Starting in MongoDB 4.0, MongoDB (Community Edition) offers free cloud monitoring for standalone and replica set deployments.从MongoDB 4.0开始,MongoDB(Community Edition)为独立和副本集部署提供免费的云监控

Note

Free cloud monitoring is only available for MongoDB Community Edition.免费云监控仅适用于MongoDB社区版。

Method方法Description描述
db.disableFreeMonitoring()Disables free cloud monitoring for your deployment.禁用部署的免费云监控。
db.enableFreeMonitoring()Enables free cloud monitoring for your deployment.为您的部署启用免费的云监控。
db.getFreeMonitoringStatus()Returns the free cloud monitoring status for your deployment.返回部署的免费云监控状态。

Client-Side Field Level Encryption Methods客户端字段级加密方法

Note

Limitations局限性

  • Automatic encryption is only available when mongosh is connected to an Atlas cluster or a MongoDB Enterprise Server. 只有当mongosh连接到Atlas集群或MongoDB Enterprise Server时,自动加密才可用。For details, see Automatic Client-Side Field Level Encryption. 有关详细信息,请参阅自动客户端字段级加密The methods listed in this section are used for manual encryption, and are supported on non-enterprise servers.本节中列出的方法用于手动加密,并且在非企业服务器上受支持。
  • Automatic encryption is not available with the Homebrew installation of mongosh.mongosh的Homebrew安装不提供自动加密功能。
  • Field level encryption is only available in the mongosh binary, and not available in the embedded Compass shell.字段级加密仅在mongosh二进制文件中可用,而在嵌入式Compass shell中不可用。
Method方法Description描述
ClientEncryption.createEncryptedCollection()Creates a collection with encrypted fields.创建具有加密字段的集合。
ClientEncryption.decrypt()Decrypts the specified encryptedValue if the current database connection was configured with access to the Key Management Service (KMS) and key vault used to encrypt encryptedValue.如果当前数据库连接配置为可以访问密钥管理服务(KMS)和用于加密encryptedValue的密钥保管库,则解密指定的encryptedValue
ClientEncryption.encrypt()Encrypts the specified value using the specified encryptionKeyId and encryptionAlgorithm.使用指定的encryptionKeyIdencryption_Algorithm对指定的值进行加密。
getClientEncryption()Returns the ClientEncryption object for the current database collection.返回当前数据库集合的ClientEncryption对象。
getKeyVault()Returns the KeyVault object for the current database connection.返回当前数据库连接的KeyVault对象。
KeyVault.addKeyAlternateName()Adds the keyAltName to the keyAltNames array of the data encryption key with the specified UUID.keyAltName添加到具有指定UUID的数据加密密钥的keyAltNames数组中。
KeyVault.createKey()Adds a data encryption key to the key vault associated to the database connection.将数据加密密钥添加到与数据库连接关联的密钥保管库中。
KeyVault.deleteKey()Deletes a data encryption key with the specified UUID from the key vault associated to the database connection.从与数据库连接关联的密钥保管库中删除具有指定UUID的数据加密密钥。
KeyVault.getKey()Gets a data encryption key with the specified UUID. 获取具有指定UUID的数据加密密钥。The data encryption key must exist in the key vault associated to the database connection.数据加密密钥必须存在于与数据库连接关联的密钥保管库中。
KeyVault.getKeyByAltName()Gets all data encryption keys with the specified keyAltName.获取具有指定keyAltName的所有数据加密密钥。
KeyVault.getKeys()Returns all data encryption keys stored in the key vault associated to the database connection.返回存储在与数据库连接关联的密钥保管库中的所有数据加密密钥。
KeyVault.removeKeyAlternateName()Removes the specified keyAltName from the data encryption key with the specified UUID. 从具有指定UUID的数据加密密钥中删除指定的keyAltNameThe data encryption key must exist in the key vault associated to the database connection.数据加密密钥必须存在于与数据库连接关联的密钥保管库中。

Native Methods原生方法

Method方法Description描述
cd()Changes the current working directory to the specified path.将当前工作目录更改为指定的路径。
isInteractive()Returns a boolean indicating whether mongosh is running in interactive or script mode.返回一个布尔值,指示mongosh是以交互模式还是脚本模式运行。
load()Loads and runs a JavaScript file in the shell.在shell中加载并运行JavaScript文件。
In mongosh, scripts loaded with the load() method support the __filename and __dirname Node.js variables. mongosh中,用load()方法加载的脚本支持__filename__dirname Node.js变量。These variables return the file name and directory of the loaded script, respectively. 这些变量分别返回加载的脚本的文件名和目录。The returned values are always absolute paths.返回的值始终是绝对路径。
In the legacy shell, you cannot not access the script's file name or directory using the load() method.在遗留shell中,不能使用load()方法不访问脚本的文件名或目录。
print()Print the specified text or variable. print() and printjson() are aliases for console.log().打印指定的文本或变量。print()printjson()console.log()的别名。
> print("hello world")
hello world

> x = "example text"
> print(x)
example text
pwd()Returns the current working directory of the active shell session.返回活动shell会话的当前工作目录。
quit()Exits the current shell session.退出当前shell会话。
sleep()Suspends the mongo shell for a given period of time.mongo shell挂起一段给定的时间。
version()Returns the current version of the mongosh instance.返回mongosh实例的当前版本。

Query Plan Cache Methods查询计划缓存方法

Method方法Description描述
db.collection.getPlanCache()Returns an interface to access the query plan cache object and associated PlanCache methods for a collection.返回一个接口,用于访问集合的查询计划缓存对象和关联的PlanCache方法。
PlanCache.clear()Removes all cached query plans for a collection.删除集合的所有缓存查询计划。
PlanCache.clearPlansByQuery()Clears the cached query plans for the specified query shape.清除指定查询形状的缓存查询计划。
PlanCache.help()Lists the methods available to view and modify a collection’s query plan cache.列出可用于查看和修改集合的查询计划缓存的方法。
PlanCache.list()Returns an array of plan cache entries for a collection.返回集合的计划缓存项的数组。

Replication Methods复制方法

Method方法Description描述
rs.add()Adds a member to the replica set. 将成员添加到副本集中。You must connect to the primary of the replica set to run this method.您必须连接到副本集的主副本才能运行此方法。
rs.addArb()Adds an arbiter to an existing replica set.将仲裁器添加到现有副本集中。
rs.config()Returns a document that contains the current replica set configuration.返回包含当前副本集配置的文档。
rs.freeze()Makes the replica set member that mongosh is connected to ineligible to become primary for the specified duration. 使mongosh连接到的副本集成员在指定的持续时间内没有资格成为主要成员。You must specify the duration in seconds.必须以秒为单位指定持续时间。
db.getReplicationInfo()Returns the status of the replica set from the oplog data.从操作日志数据中返回复制副本集的状态。
rs.initiate()Initializes a new replica set.初始化新的复制副本集。
db.printReplicationInfo()Returns the oplog of the replica set member that mongosh is connected to.返回mongosh连接到的副本集成员的操作日志。
rs.printReplicationInfo()Returns the oplog of the replica set member that mongosh is connected to.返回mongosh连接到的副本集成员的操作日志。
db.printSecondaryReplicationInfoReturns the status of the secondary members of the replica set.返回复制副本集的辅助成员的状态。
This is identical to the rs.printSecondaryReplicationInfo() method. 这与rs.printSecondaryReplicationInfo()方法相同。This method's output is similar to the db.printSlaveReplicationInfo() method. 此方法的输出类似于db.printSlaveReplicationInfo()方法。The db.printSlaveReplicationInfo() method is deprecated in mongosh. mongosh中不赞成使用db.printSlaveReplicationInfo()方法。Use db.printSecondaryReplicationInfo() instead.请改用db.printSecondaryReplicationInfo()
The following is an example output from the rs.printSecondaryReplicationInfo() method issued on a replica set with two secondary members:以下是在具有两个辅助成员的副本集上发出的rs.printSecondaryReplicationInfo()方法的输出示例:
source: rs2.example.net:27017
{
syncedTo: 'Tue Oct 13 2020 09:37:28 GMT-0700 (Pacific Daylight Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
---
source: rs3.example.net:27017
{
syncedTo: 'Tue Oct 13 2020 09:37:28 GMT-0700 (Pacific Daylight Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
rs.printSecondaryReplicationInfoReturns the status of the secondary members of the replica set.返回复制副本集的辅助成员的状态。
This is identical to the db.printSecondaryReplicationInfo() method. 这与db.printSecondaryReplicationInfo()方法相同。This method's output is similar to the rs.printSlaveReplicationInfo() method in the legacy mongo shell. 该方法的输出类似于遗留mongo shell中的rs.printSlaveReplicationInfo()方法。The rs.printSlaveReplicationInfo() method is deprecated in mongosh. rs.printSlaveReplicationInfo()方法在mongosh中已被弃用。Use rs.printSecondaryReplicationInfo() instead.请改用rs.printSecondaryReplicationInfo()
The following is an example output from the rs.printSecondaryReplicationInfo() method issued on a replica set with two secondary members:以下是在具有两个辅助成员的副本集上发出的rs.printSecondaryReplicationInfo()方法的输出示例:
source: rs2.example.net:27017
{
syncedTo: 'Tue Oct 13 2020 09:42:18 GMT-0700 (Pacific Daylight Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
---
source: rs3.example.net:27017
{
syncedTo: 'Tue Oct 13 2020 09:42:18 GMT-0700 (Pacific Daylight Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
rs.reconfig()Modifies the configuration of an existing replica set.修改现有复制副本集的配置。
rs.remove()Removes the member specified by hostname from the replica set.从副本集中删除由主机名指定的成员。
rs.status()Returns the status of the replica set member that mongosh is connected to.返回mongosh连接到的副本集成员的状态。
rs.stepDown()Makes the primary of the replica set a secondary. 使复制副本集的主副本成为辅助副本。You must be connected to the primary to run this method.您必须连接到主服务器才能运行此方法。
rs.syncFrom()Resets the sync target to the replica set member specified by hostname for the replica set member that mongosh is connected to.将同步目标重置为mongosh所连接的副本集成员的主机名指定的副本集。

Role Management Methods角色管理方法

Method方法Description描述
db.createRole()Creates a role and specifies its privileges.创建角色并指定其权限。
db.dropRole()Deletes a user-defined role.删除用户定义的角色。
db.dropAllRoles()Deletes all user-defined roles associated with a database.删除与数据库关联的所有用户定义的角色。
db.getRole()Returns information for the specified role.返回指定角色的信息。
db.getRoles()Returns information for all the user-defined roles in a database.返回数据库中所有用户定义角色的信息。
db.grantPrivilegesToRole()Assigns privileges to a user-defined role.为用户定义的角色分配权限。
db.revokePrivilegesFromRole()Removes the specified privileges from a user-defined role.从用户定义的角色中删除指定的权限。
db.grantRolesToRole()Specifies roles from which a user-defined role inherits privileges.指定用户定义的角色从中继承权限的角色。
db.revokeRolesFromRole()Removes inherited roles from a role.从角色中删除继承的角色。
db.updateRole()Updates a user-defined role.更新用户定义的角色。

Session Object Methods会话对象方法

Method方法Description描述
Mongo.startSession()Starts a session for the connection.为连接启动会话。
Session.advanceOperationTime()Updates the operation time.更新操作时间。
Session.endSession()Ends the session.结束会话。
Session.getClusterTime()Returns the most recent cluster time as seen by the session.返回会话看到的最近的群集时间。
Session.getDatabase()Access the specified database from the session in the shell.从shell中的会话访问指定的数据库。
Session.getOperationTime()Returns the timestamp of the last acknowledged operation for the session.返回会话最后一次确认操作的时间戳。
Session.getOptions()Returns the options for the session.返回会话的选项。
Session.hasEnded()Returns a boolean that specifies whether the session has ended.返回一个布尔值,用于指定会话是否已结束。
SessionOptions()The options for a session in the shell. shell中会话的选项。To access the SessionOptions() object, use Session.getOptions().要访问SessionOptions()对象,请使用Session.getOptions()

Server Status Methods服务器状态方法

Method方法Description描述
db.hello()Returns a document that describes the role of the mongod instance.返回一个文档,该文档描述mongod实例的角色。
If the mongod is a member of a replica set, then the isWritablePrimary and secondary fields report if the instance is the primary or if it is a secondary member of the replica set.如果mongod是副本集的成员,则isWritablePrimarysecondary字段会报告该实例是副本集中的主要成员还是次要成员。
db.hostInfo()Returns a document with information about the system running the MongoDB instance.返回一个文档,其中包含有关运行MongoDB实例的系统的信息。
db.collection.latencyStats()Returns latency statistics for a specified collection.返回指定集合的延迟统计信息。
db.printCollectionStats()Returns statistics from every collection.返回每个集合的统计信息。
db.serverBuildInfo()Returns a document that displays the compilation parameters for the mongod instance.返回一个文档,该文档显示mongod实例的编译参数。
db.serverCmdLineOpts()Returns a document with information about the runtime options used to start the MongoDB instance.返回一个文档,其中包含有关用于启动MongoDB实例的运行时选项的信息。
db.serverStatus()Returns a document that provides an overview of the database process.返回一个提供数据库进程概述的文档。
db.stats()Returns a document that reports on the state of the current database.返回一个报告当前数据库状态的文档。
db.version()Returns the version of the mongod instance.返回mongod实例的版本。

Sharding Methods分片方法

Method方法Description描述
sh.addShard()Adds a shard to a sharded cluster.将分片添加到已分片化的群集中。
sh.addShardTag()Aliases to sh.addShardToZone().sh.addShardToZone()的别名。
sh.addShardToZone()Associates a shard with a zone. Supports configuring zones in sharded clusters.将分片与区域关联。支持在分片集群中配置区域。
sh.addTagRange()Aliases to sh.updateZoneKeyRange().sh.updateZoneKeyRange()的别名。
sh.balancerCollectionStatus()Returns information on whether the chunks of a sharded collection are balanced.返回有关分片集合的块是否平衡的信息。
New in version 4.4.4.4版新增。
sh.disableAutoMerger()Disables automatic chunk merges for a namespace.禁用命名空间的自动块合并。
New in version 7.0.7.0版新增。
sh.disableAutoSplit()Disables auto-splitting for the sharded cluster.禁用分片群集的自动拆分。
sh.disableBalancing()Disables balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.禁用在分片数据库中的单个集合上进行平衡。不影响分片集群中其他集合的平衡。
sh.enableAutoMerger()Enables automatic chunk merges for a namespace.启用命名空间的自动块合并。
New in version 7.0.7.0版新增。
sh.enableAutoSplit()Enables auto-splitting for the sharded cluster.启用分片集群的自动拆分。
sh.enableBalancing()Activates the sharded collection balancer process if previously disabled using sh.disableBalancing().如果之前使用sh.disableBalancing()禁用了分片集合平衡器进程,则激活该进程。
sh.enableSharding()Enables sharding on a specific database.在特定数据库上启用分片。
sh.getBalancerState()Returns a boolean to report if the balancer is currently enabled.如果平衡器当前已启用,则返回要报告的布尔值。
sh.isBalancerRunning()Returns a boolean to report if the balancer process is currently migrating chunks.如果平衡器进程当前正在迁移块,则返回一个布尔值以报告。
sh.moveChunk()Migrates a chunk in a sharded cluster.迁移分片集群中的区块
sh.removeRangeFromZone()Removes the association between a range of shard key values and a zone.删除一系列分片键值和区域之间的关联。
sh.removeShardFromZone()Removes the association between a shard and a zone.删除分片和区域之间的关联。
sh.removeShardTag()Removes the association between a tag and a shard.删除标记和分片之间的关联。
sh.removeTagRange()Removes a range of shard key values to a shard tag created using the sh.addShardTag() method. 将一系列shard键值移除到使用sh.addShardTag()方法创建的shard标记中。This method aliases to sh.removeRangeFromZone() in MongoDB 3.4.此方法别名为MongoDB 3.4中的sh.removeRangeFromZone()
sh.setBalancerState()Enables or disables the balancer which migrates chunks between shards.启用或禁用在分片之间迁移平衡器
sh.shardCollection()Enables sharding for a collection.启用集合的分片。
sh.splitAt()Divides an existing chunk into two chunks using a specific value of the shard key as the dividing point.使用分片键的特定值作为分割点,将现有划分为两个块。
sh.splitFind()Divides an existing chunk that contains a document matching a query into two approximately equal chunks.将包含与查询匹配的文档的现有块划分为两个大致相等的
sh.startAutoMerger()Enables the AutoMerger.启用自动合并。
New in version 7.0.7.0版新增。
sh.startBalancer()Enables the balancer.启用平衡器
sh.status()Reports on the status of a sharded cluster.报告分片集群的状态。
sh.stopAutoMerger()Disables the AutoMerger.禁用自动合并。
New in version 7.0.7.0版新增。
sh.stopBalancer()Disables the balancer. 禁用平衡器This operation does not wait for the balancer to complete any in progress operations, and may terminate ongoing operations.此操作不会等待平衡器完成任何正在进行的操作,并且可能会终止正在进行的作业。
sh.updateZoneKeyRange()Associates a range of shard keys with a zone. 将一系列分片关键帧与区域关联。Supports configuring zones in sharded clusters.支持在分片集群中配置区域。

Telemetry Methods遥测方法

These methods configure whether mongosh tracks anonymous telemetry data. 这些方法配置mongosh是否跟踪匿名遥测数据。Telemetry is enabled by default.默认情况下启用遥测。

For more information on what data mongosh tracks with telemetry, see Configure Telemetry Options.有关mongosh使用遥测跟踪哪些数据的详细信息,请参阅配置遥测选项

Method方法Description描述
disableTelemetry()Disable telemetry for mongosh.禁用mongosh的遥测。
enableTelemetry()Enable telemetry for mongosh.启用mongosh的遥测。

Transaction Methods事务处理方法

Method方法Description描述
Session.abortTransaction()Terminates a multi-document transaction and rolls back any data changes made by the operations within the transaction.终止多文档事务,并回滚事务中操作所做的任何数据更改。
Session.commitTransaction()Saves the changes made by the operations in a multi-document transaction and ends the transaction.保存多文档事务中的操作所做的更改并结束事务。
Session.startTransaction()Starts a multi-document transaction associated with the session.启动与会话关联的多文档事务

User Management Methods用户管理方法

Important

The passwordPrompt() method is currently not supported in mongosh. mongosh当前不支持passwordPrompt()方法。As a result, when using the following methods you must specify the password as a parameter:因此,使用以下方法时,必须将密码指定为参数:

Method方法Description描述
db.auth()Authenticates a user to a database.对数据库的用户进行身份验证。
db.changeUserPassword()Changes an existing user’s password.更改现有用户的密码。
db.createUser()Creates a new user.创建新用户。
db.dropAllUsers()Deletes all users associated with a database.删除与数据库关联的所有用户。
db.dropUser()Deletes a single user.删除单个用户。
db.getUser()Returns information about the specified user.返回有关指定用户的信息。
db.getUsers()Returns information about all users associated with a database.返回与数据库关联的所有用户的信息。
db.updateUser()Updates a specified user's data.更新指定用户的数据。
db.grantRolesToUser()Grants a role and its privileges to a user.将角色及其权限授予用户。
db.revokeRolesFromUser()Removes a role from a user.从用户中删除角色。