Docs Home / mongosh / Reference

Methods方法

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

Important

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

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

  • 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搜索索引允许您在Atlas搜索中查询数据。Atlas Search indexes enable performant text search queries by mapping search terms to the documents that contain those terms.Atlas搜索索引通过将搜索词映射到包含这些词的文档来实现高性能的文本搜索查询。

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

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搜索索引。
db.collection.dropSearchIndex()Deletes an existing Atlas Search index.删除现有的Atlas搜索索引。
db.collection.getSearchIndexes()Returns information about existing Atlas Search indexes on a specified collection.返回指定集合上现有Atlas搜索索引的信息。
db.collection.updateSearchIndex()Updates an existing Atlas Search index.更新现有的Atlas搜索索引。

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. The builder constructs an unordered list of write operations that MongoDB executes in bulk.初始化并返回集合的新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.设置hint(提示)选项,该选项指定支持批量操作的索引。
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. The method updates specific fields in existing documents.multi更新操作添加到批量操作列表中。该方法更新现有文档中的特定字段。
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. Use db.collection.countDocuments() or db.collection.estimatedDocumentCount() instead.mongosh 1.0.6中已弃用。请改用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.返回集合的大小。将size字段包裹在collStats的输出中。
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()Returns information regarding the state of data in a sharded cluster.返回有关分片集群中数据状态的信息。
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描述

host

string

Optional可选的

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接口的连接。

autoEncryptionOptsDocument

Optional可选的

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连接的config读取首选项。
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.打开副本集或分片群集的更改流游标,以报告其数据库中的所有非系统集合,但adminlocalconfig数据库除外。

Cursor Methods游标方法

Method方法Description描述
cursor.addOption()Adds special wire protocol flags that modify the behavior of the query.添加修改查询行为的特殊有线协议标志。
cursor.batchSize()

Specifies the maximum number of documents MongoDB can return to the client within each batch returned in a query result. 指定MongoDB在查询结果中返回的每个批中可以返回给客户端的最大文档数。By default, the initial batch size is the lesser of 101 documents or 16 mebibytes (MiB) worth of documents. Subsequent batches have a maximum size of 16 MiB. 默认情况下,初始批大小为101个文档或价值16兆字节(MiB)的文档中的较小者。后续批次的最大容量为16 MiB。This option can enforce a smaller limit than 16 MiB, but not a larger one. When set, the batchSize is the lesser of batchSize documents or 16 MiB worth of documents.此选项可以强制执行小于16 MiB的限制,但不能强制执行更大的限制。设置后,batchSizebatchSize文档或价值16 MiB的文档中的较小值。

A batchSize of 0 means that the cursor is established, but no documents are returned in the first batch.batchSize0表示游标已建立,但第一批中没有返回文档。

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.在查询中附加注释,以允许日志和系统配置文件集合中的可追溯性。
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.打开数据库的更改流游标,以报告其所有非系统集合。

In-Use 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 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.使用指定的encryptionKeyIdencryptionAlgorithm对指定值进行加密。
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. The data encryption key must exist in the key vault associated to the database connection.获取具有指定UUID的数据加密键。数据加密键必须存在于与数据库连接关联的键库中。
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描述

buildInfo()

Returns the following JSON-formatted document that describes your mongosh build and driver dependencies:返回以下JSON格式的文档,描述mongosh构建和驱动程序依赖关系:

{
version: '1.10.1',
distributionKind: 'packaged',
buildArch: 'x64',
buildPlatform: 'linux',
buildTarget: 'unknown',
buildTime: '2023-06-21T09:49:37.225Z',
gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7',
nodeVersion: 'v16.20.1',
opensslVersion: '3.1.1',
sharedOpenssl: true,
runtimeArch: 'x64',
runtimePlatform: 'darwin',
deps: {
nodeDriverVersion: '5.6.0',
libmongocryptVersion: undefined,
libmongocryptNodeBindingsVersion: undefined
}
}

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. These variables return the file name and directory of the loaded script, respectively. The returned values are always absolute paths.mongosh中,使用load()方法加载的脚本支持__filename__dirname Node.js变量。这些变量分别返回加载脚本的文件名和目录。返回的值始终是绝对路径。

The legacy mongo shell cannot access a script's file name or directory in the load() method.旧版mongo 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

quit()

Exits the current shell session.退出当前shell会话。

sleep()

Suspends the mongo shell for a given period of time.将猫砂壳悬挂一段时间。

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. You must specify the duration in seconds.使mongosh连接到的副本集成员在指定的持续时间内没有资格成为主要成员。您必须以秒为单位指定持续时间。
db.getReplicationInfo()Returns the status of the replica set from the oplog data.从oplog数据返回副本集的状态。
rs.initiate()Initializes a new replica set.初始化新的副本集。
db.printReplicationInfo()Returns the oplog of the replica set member that mongosh is connected to.返回mongosh连接到的副本集成员的oplog。
rs.printReplicationInfo()Returns the oplog of the replica set member that mongosh is connected to.返回mongosh连接到的副本集成员的oplog。
db.printSecondaryReplicationInfo

Returns the status of the secondary members of the replica set.返回副本集次要成员的状态。

This is identical to the rs.printSecondaryReplicationInfo() method.这与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: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.printSecondaryReplicationInfo

Returns the status of the secondary members of the replica set.返回副本集secondary成员的状态。

This is identical to the db.printSecondaryReplicationInfo() method.这与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: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. To access the SessionOptions() object, use Session.getOptions().shell中会话的选项。要访问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字段会报告该实例是副本集中的primary成员还是secondary成员。

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描述
db.collection.getShardLocation()Returns a document containing the shards where the collection is located and whether the collection is sharded.返回一个文档,其中包含集合所在的分片以及集合是否分片。
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.disableMigrations()Disables chunk migrations for a specific collection in a sharded cluster. Internally calls the setAllowMigrations command.禁用分片集群中特定集合的块迁移。在内部调用setAllowMigrations命令。
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.enableMigrations()Enables chunk migrations for a specific collection in a sharded cluster that were previously disabled using sh.disableMigrations(). 为之前使用sh.disableMigrations()禁用的分片群集中的特定集合启用块迁移。Internally calls the setAllowMigrations command.在内部调用setAllowMigrations命令。
sh.enableSharding()Enables sharding on a specific database.在特定数据库上启用分片。
sh.getBalancerState()Returns a boolean to report if the balancer is currently enabled.返回一个布尔值,用于报告平衡器当前是否已启用。
sh.getShardedDataDistribution()Returns data distribution information for sharded collections. 返回分片集合的数据分布信息。sh.getShardedDataDistribution() is a shell helper method for the $shardedDataDistribution aggregation pipeline stage.$shardedDataDistribution聚合管道阶段的shell辅助方法。
sh.isBalancerRunning()Returns a boolean to report if the balancer process is currently migrating chunks.返回一个布尔值,用于报告平衡器进程当前是否正在迁移块。
sh.isConfigShardEnabled()Returns whether a cluster has a config shard. If it does, sh.isConfigShardEnabled() also returns host and tag information.返回集群是否有配置分片。如果是这样,sh.isConfigShardEnabled()也会返回主机和标签信息。
sh.listShards()Returns an array of documents describing the shards in a sharded cluster.返回描述分片集群中分片的文档数组。
sh.moveChunk()Migrates a chunk in a sharded cluster.迁移chunk in a 分片集群中的块。
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. 将一系列分片键值删除到使用sh.addShardTag()方法创建的分片标记中。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. Telemetry is enabled by default.这些方法配置mongosh是否跟踪匿名遥测数据。默认情况下启用遥测。

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. As a result, when using the following methods you must specify the password as a parameter:mongosh当前不支持passwordPrompt()方法。因此,使用以下方法时,必须将密码指定为参数:

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.从用户中删除角色。