Docs HomeMongoDB Manual

mongosh Methods方法

Note

JavaScript in MongoDBMongoDB中的JavaScript

Although these methods use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.尽管这些方法使用JavaScript,但与MongoDB的大多数交互都不使用JavaScript,而是使用交互应用程序语言中的惯用驱动程序

Note

For details on a specific method, including syntax and examples, click on the link to the method's reference page.有关特定方法的详细信息,包括语法和示例,请单击该方法参考页的链接。

Collection集合

Name名称Description描述
db.collection.analyzeShardKey()Calculates metrics for evaluating a shard key.计算用于评估分片键的度量。
db.collection.aggregate()Provides access to the aggregation pipeline.提供对聚合管道的访问。
db.collection.bulkWrite()Provides bulk write operation functionality.提供大容量写入操作功能。
db.collection.compactStructuredEncryptionData()Wraps compactStructuredEncryptionData to return a success or failure object.包装compactStructuredEncryptionData以返回成功或失败对象。
db.collection.configureQueryAnalyzer()Configures query sampling for a collection.配置集合的查询采样。
db.collection.count()Wraps count to return a count of the number of documents in a collection or a view.包装count可返回集合或视图中文档数的计数。
db.collection.countDocuments()Wraps the $group aggregation stage with a $sum expression to return a count of the number of documents in a collection or a view.$sum表达式包装$group聚合阶段,以返回集合或视图中文档数的计数。
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()Removed. 已删除。Use db.collection.createIndex().请改用db.collection.createIndex()
db.collection.estimatedDocumentCount()Wraps count to return an approximate count of the documents in a collection or a view.包装count可返回集合或视图中文档的近似计数。
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()For collections in sharded clusters, db.collection.getShardDistribution() reports data of chunk distribution.对于分片集群中的集合,db.collection.getShardDistribution()报告区块分布的数据。
db.collection.getShardVersion()Internal diagnostic method for sharded cluster.分片集群的内部诊断方法。
db.collection.hideIndex()Hides an index from the query planner.从查询计划器隐藏索引。
db.collection.insertOne()Inserts a new document into a collection.将新文档插入集合中。
db.collection.insertMany()Inserts several new documents into a collection.在集合中插入几个新文档。
db.collection.isCapped()Reports if a collection is a capped collection.报告集合是否为上限集合
db.collection.latencyStats()Returns latency statistics for a collection.返回集合的延迟统计信息。
db.collection.mapReduce()Performs map-reduce style data aggregation.执行映射缩减样式的数据聚合。
db.collection.reIndex()Rebuilds all existing indexes on a collection.重新生成集合上的所有现有索引。
db.collection.remove()Deletes documents from 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.unhideIndex()Unhides an index from the query planner.取消隐藏查询计划器中的索引。
db.collection.updateOne()Modifies a single document in a collection.修改集合中的单个文档。
db.collection.updateMany()Modifies multiple documents in a collection.修改集合中的多个文档。
db.collection.watch()Establishes a Change Stream on a collection.在集合上建立变更流。
db.collection.validate()Performs diagnostic operations on a collection.对集合执行诊断操作。

Cursor游标

Name名称Description描述
cursor.addOption()Adds special wire protocol flags that modify the behavior of the query.'添加用于修改查询行为的特殊连线协议标志。
cursor.allowDiskUse()Allows MongoDB to use temporary files on disk to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.允许MongoDB在处理阻塞排序操作时使用磁盘上的临时文件来存储超过100兆字节系统内存限制的数据。
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在单个网络消息中返回给客户端的文档数量。
cursor.close()Close a cursor and free associated server resources.关闭游标并释放关联的服务器资源。
cursor.isClosed()Returns true if the cursor is closed.如果游标关闭,则返回true
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.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.pretty()Configures the cursor to display results in an easy-to-read format.将游标配置为以易读的格式显示结果。
cursor.readConcern()Specifies a read concern for a find() operation.指定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数据库

Name名称Description描述
db.adminCommand()Runs a command against the admin database.admin数据库运行命令。
db.aggregate()Runs admin/diagnostic pipeline which does not require an underlying collection.运行不需要基础集合的管理/诊断管道。
db.commandHelp()Returns help information for a database command.返回数据库命令的帮助信息。
db.createCollection()Creates a new collection or a view. 创建新集合或视图。Commonly used to create a capped collection.通常用于创建封顶集合。
db.createView()Creates a view.创建视图。
db.currentOp()Reports the current in-progress operations.报告当前正在进行的操作。
db.dropDatabase()Removes the current database.删除当前数据库。
db.fsyncLock()Flushes writes to disk and locks the database to prevent write operations and assist backup operations. 刷新对磁盘的写入并锁定数据库,以防止写入操作并协助备份操作。Wraps fsync.包装fsync
db.fsyncUnlock()Allows writes to continue on a database locked with db.fsyncLock().允许在使用db.fsyncLock()锁定的数据库上继续写入。
db.getCollection()Returns a collection or view object. 返回集合或视图对象。Used to access collections with names that are not valid in mongosh.用于访问名称在mongosh中无效的集合。
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.getLogComponents()Returns the log message verbosity levels.返回日志消息详细级别。
db.getMongo()Returns the Mongo() connection object for the current connection.返回当前连接的Mongo()连接对象。
db.getName()Returns the name of the current database.返回当前数据库的名称。
db.getProfilingStatus()Returns a document that reflects the current profiling level and the profiling threshold.返回反映当前分析级别和分析阈值的文档。
db.getReplicationInfo()Returns a document with replication statistics.返回包含复制统计信息的文档。
db.getSiblingDB()Provides access to the specified database.提供对指定数据库的访问权限。
db.hello()Returns a document that reports the state of the replica set.返回一个报告副本集状态的文档。
db.help()Displays descriptions of common db object methods.显示常用数据库对象方法的说明。
db.hostInfo()Returns a document with information about the system MongoDB runs on. 返回一个文档,其中包含有关MongoDB运行系统的信息。Wraps hostInfo包装hostInfo
db.killOp()Terminates a specified operation.终止指定的操作。
db.listCommands()Displays a list of common database commands.显示常用数据库命令的列表。
db.logout()Deprecated. 已弃用。Ends an authenticated session.结束经过身份验证的会话。
db.printCollectionStats()Prints statistics from every collection. 打印每个集合的统计信息。Wraps db.collection.stats().包装db.collection.stats()
db.printReplicationInfo()Prints a report of the status of the replica set from the perspective of the primary.从主副本的角度打印副本集的状态报告。
db.printSecondaryReplicationInfo()Prints the status of the replica set from the perspective of the secondaries.从辅助副本的角度打印副本集的状态。
db.printShardingStatus()Prints a report of the sharding configuration and the chunk ranges.打印分片配置和区块范围的报告。
db.printSlaveReplicationInfo()Deprecated since version 4.4.1:自4.4.1版起弃用: Use db.printSecondaryReplicationInfo() instead. 请改用db.printSecondaryReplicationInfo()
db.resetError()Removed in MongoDB 5.0.在MongoDB 5.0中删除。 Resets the last error status.重置上次错误状态。
db.rotateCertificates()Performs online TLS certificate rotation. 执行联机TLS证书轮换。Wraps rotateCertificates.包装rotateCertificates
db.runCommand()Runs a database command.运行数据库命令
db.serverBuildInfo()Returns a document that displays the compilation parameters for the mongod instance. 返回一个文档,该文档显示mongod实例的编译参数。Wraps buildInfo.包装buildInfo
db.serverCmdLineOpts()Returns a document with information about the runtime used to start the MongoDB instance. 返回一个文档,其中包含用于启动MongoDB实例的运行时信息。Wraps getCmdLineOpts.包装getCmdLineOpts
db.serverStatus()Returns a document that provides an overview of the state of the database process.返回一个文档,该文档概述了数据库进程的状态。
db.setLogLevel()Sets a single log message verbosity level.设置单个日志消息的详细级别。
db.setProfilingLevel()Modifies the current level of database profiling.修改数据库分析的当前级别。
db.shutdownServer()Shuts down the current mongod or mongos process cleanly and safely.干净安全地关闭当前mongodmongos进程。
db.stats()Returns a document that reports on the state of the current database.返回一个报告当前数据库状态的文档。
db.version()Returns the version of the mongod instance.返回mongod实例的版本。
db.watch()Opens a change stream cursor for a database to report on all its non-system collections. 打开数据库的更改流游标,以报告其所有非system集合。Cannot be opened on the admin, local or config databases.无法在admin数据库、local数据库或config数据库上打开。

Query Plan Cache查询计划缓存

Name名称Description描述
db.collection.getPlanCache()Returns an interface to access the query plan cache object and associated PlanCache methods for a collection.返回一个接口,用于访问集合的查询计划缓存对象和关联的PlanCache方法。
PlanCache.clear()Clears all the cached query plans for a collection. 清除集合的所有缓存查询计划。Accessible through the plan cache object of a specific collection, i.e. db.collection.getPlanCache().clear().可通过特定集合的计划缓存对象访问,即db.collection.getPlanCache().clear()
PlanCache.clearPlansByQuery()Clears the cached query plans for the specified query shape. 清除指定查询形状的缓存查询计划。Accessible through the plan cache object of a specific collection, i.e. db.collection.getPlanCache().clearPlansByQuery()可通过特定集合的计划缓存对象访问,即db.collection.getPlanCache().clearPlansByQuery()
PlanCache.help()Displays the methods available for a collection's query plan cache. Accessible through the plan cache object of a specific collection, i.e. db.collection.getPlanCache().help().显示可用于集合的查询计划缓存的方法。可通过特定集合的计划缓存对象访问,即db.collection.getPlanCache().help()
PlanCache.list()Returns the plan cache information for a collection. 返回集合的计划缓存信息。Accessible through the plan cache object of a specific collection, i.e. db.collection.getPlanCache().list(). 可通过特定集合的计划缓存对象访问,即db.collection.getPlanCache().list()
New in version 4.4. 4.4版新增。

Bulk Write Operation大容量写入操作

Name名称Description描述
db.collection.initializeOrderedBulkOp()Initializes a Bulk() operations builder for an ordered list of operations.为有序的操作列表初始化Bulk()操作生成器。
db.collection.initializeUnorderedBulkOp()Initializes a Bulk() operations builder for an unordered list of operations.为无序的操作列表初始化Bulk()操作生成器。
Bulk()Bulk operations builder.批量操作生成器。
Bulk.execute()Executes a list of operations in bulk.批量执行操作列表。
Bulk.find()Specifies the query condition for an update or a remove operation.指定更新或删除操作的查询条件。
Bulk.find.arrayFilters()Specifies the filters that determine which elements of an array to update for an update or updateOne operation.指定筛选器,用于确定要为updateupdateOne操作更新数组中的哪些元素。
Bulk.find.collation()Specifies the collation for the query condition.指定查询条件的排序规则
Bulk.find.delete()Adds a multiple document delete operation to a list of operations.将多文档删除操作添加到操作列表中。
Bulk.find.deleteOne()Adds a single document delete operation to a list of operations.将单个文档删除操作添加到操作列表中。
Bulk.find.hint()Specifies the index to use for the update/replace operation.指定用于更新/替换操作的索引。
Bulk.find.remove()An alias for Bulk.find.delete().Bulk.find.delete()的别名。
Bulk.find.removeOne()An alias for Bulk.find.deleteOne().Bulk.find.deleteOne()的别名。
Bulk.find.replaceOne()Adds a single document replacement operation to a list of operations.将单个文档替换操作添加到操作列表中。
Bulk.find.updateOne()Adds a single document update operation to a list of operations.将单个文档更新操作添加到操作列表中。
Bulk.find.update()Adds a multi update operation to a list of operations.multi更新操作添加到操作列表中。
Bulk.find.upsert()Specifies upsert: true for an update operation.为更新操作指定upsert: true
Bulk.getOperations()Returns an array of write operations executed in the Bulk() operations object.返回在Bulk()操作对象中执行的写入操作的数组。
Bulk.insert()Adds an insert operation to a list of operations.将插入操作添加到操作列表中。
Bulk.toJSON()Returns a JSON document that contains the number of operations and batches in the Bulk() operations object.返回一个JSON文档,该文档包含Bulk()操作对象中的操作数和批处理数。
Bulk.toString()Returns the Bulk.toJSON() results as a string.以字符串形式返回Bulk.toJSON()结果。

User Management用户管理

Name名称Description描述
db.auth()Authenticates a user to a database.对数据库的用户进行身份验证。
db.changeUserPassword()Changes an existing user's password.更改现有用户的密码。
db.createUser()Creates a new user.创建新用户。
db.dropUser()Removes a single user.删除单个用户。
db.dropAllUsers()Deletes all users associated with a database.删除与数据库关联的所有用户。
db.getUser()Returns information about the specified user.返回有关指定用户的信息。
db.getUsers()Returns information about all users associated with a database.返回与数据库关联的所有用户的信息。
db.grantRolesToUser()Grants a role and its privileges to a user.将角色及其权限授予用户。
db.removeUser()Deprecated. 已弃用。Removes a user from a database.从数据库中删除用户。
db.revokeRolesFromUser()Removes a role from a user.从用户中删除角色。
db.updateUser()Updates user data.更新用户数据。
passwordPrompt()Prompts for the password as an alternative to specifying passwords directly in various mongosh user authentication/management methods.提示输入密码,以代替在各种mongosh用户身份验证/管理方法中直接指定密码。

Role Management角色管理

Name名称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.更新用户定义的角色。

Replication复制

Name名称Description描述
rs.add()Adds a member to a replica set.将成员添加到副本集中。
rs.addArb()Adds an arbiter to a replica set.仲裁器添加到副本集中。
rs.conf()Returns the replica set configuration document.返回副本集配置文档。
rs.freeze()Prevents the current member from seeking election as primary for a period of time.阻止当前成员在一段时间内以初选身份寻求选举。
rs.help()Returns basic help text for replica set functions.返回副本集函数的基本帮助文本。
rs.initiate()Initializes a new replica set.初始化新的复制副本集。
rs.printReplicationInfo()Prints a formatted report of the replica set status from the perspective of the primary.从主副本的角度打印副本集状态的格式化报告。
rs.printSecondaryReplicationInfo()Prints a formatted report of the replica set status from the perspective of the secondaries.从辅助设备的角度打印副本集状态的格式化报告。
rs.printSlaveReplicationInfo()Deprecated since version 4.4.1:自4.4.1版起弃用: Use rs.printSecondaryReplicationInfo() instead. 请改用rs.printSecondaryReplicationInfo()
rs.reconfig()Re-configures a replica set by applying a new replica set configuration object.通过应用新的副本集配置对象来重新配置副本集。
rs.remove()Remove a member from a replica set.从副本集中删除成员。
rs.status()Returns a document with information about the state of the replica set.返回一个文档,其中包含有关副本集状态的信息。
rs.stepDown()Causes the current primary to become a secondary which forces an election.使当前的primary变为secondary,从而强制进行选举
rs.syncFrom()Sets the member that this replica set member will sync from, overriding the default sync target selection logic.设置此副本集成员将从中同步的成员,覆盖默认的同步目标选择逻辑。

Sharding分片

Name名称Description描述
sh.abortReshardCollection()Aborts a resharding operation. 中止重新分片操作
New in version 5.0. 5.0版新增。
sh.addShard()Adds a shard to a sharded cluster.分片添加到已分片化的群集中。
sh.addShardTag()In MongoDB 3.4, this method aliases to sh.addShardToZone().在MongoDB 3.4中,此方法别名为sh.addShardToZone()
sh.addShardToZone()Associates a shard to a zone. 将分片与区域关联。Supports configuring zones in sharded clusters.支持在分片集群中配置区域
sh.addTagRange()In MongoDB 3.4, this method aliases to sh.updateZoneKeyRange().在MongoDB 3.4中,此方法别名为sh.updateZoneKeyRange()
sh.balancerCollectionStatus()Returns information on whether the chunks of a sharded collection are balanced. 返回有关分片集合的块是否平衡的信息。
New in version 4.4. 4.4版新增。
sh.commitReshardCollection()Forces a resharding operation to block writes and complete. 强制重新分片操作以阻止写入并完成。
New in version 5.0. 5.0版新增。
sh.disableBalancing()Disable balancing on a single collection in a sharded database. 在分片数据库中禁用对单个集合的平衡。Does not affect balancing of other collections in a sharded cluster.不影响分片集群中其他集合的平衡。
sh.enableBalancing()Activates the sharded collection balancer process if previously disabled using sh.disableBalancing().如果之前使用sh.disableBalancing()禁用了分片集合平衡器进程,则激活该进程。
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.禁用分片集群的自动拆分。
Starting in MongoDB 6.1, automatic chunk splitting is not performed. 从MongoDB 6.1开始,不执行自动区块分割。This is because of balancing policy improvements. 这是因为平衡政策的改进。Auto-splitting commands still exist, but do not perform an operation. 自动拆分命令仍然存在,但不执行操作。For details, see Balancing Policy Changes. 有关详细信息,请参阅平衡策略更改
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.启用分片集群的自动拆分。
Starting in MongoDB 6.1, automatic chunk splitting is not performed. 从MongoDB 6.1开始,不执行自动区块分割。This is because of balancing policy improvements. 这是因为平衡政策的改进。Auto-splitting commands still exist, but do not perform an operation. 自动拆分命令仍然存在,但不执行操作。For details, see Balancing Policy Changes. 有关详细信息,请参阅平衡策略更改
sh.enableSharding()Creates a database.创建数据库。
sh.getBalancerState()Returns a boolean to report if the balancer is currently enabled.如果平衡器当前已启用,则返回要报告的布尔值。
sh.removeTagRange()In MongoDB 3.4, this method aliases to sh.removeRangeFromZone().在MongoDB 3.4中,此方法别名为sh.removeRangeFromZone()
sh.removeRangeFromZone()Removes an association between a range of shard keys and a zone. 删除一系列分片关键帧和区域之间的关联。Supports configuring zones in sharded clusters.支持在分片集群中配置区域
sh.help()Returns help text for the sh methods.返回sh方法的帮助文本。
sh.isBalancerRunning()Returns a document describing the status of the balancer.返回描述平衡器状态的文档。
sh.moveChunk()Migrates a chunk in a sharded cluster.迁移分片集群中的区块
sh.removeShardTag()In MongoDB 3.4, this method aliases to sh.removeShardFromZone().在MongoDB 3.4中,此方法别名为sh.removeShardFromZone()
sh.removeShardFromZone()Removes the association between a shard and a zone. 删除分片和区域之间的关联。Use to manage zone sharding.用于管理区域分片
sh.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版新增。
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 and waits for balancing to start.启用平衡器并等待开始平衡。
sh.status()Reports on the status of a sharded cluster, as db.printShardingStatus().报告分片集群的状态,如db.printShardingStatus()
sh.stopAutoMerger()Disables the AutoMerger. 禁用自动合并
New in version 7.0. 7.0版新增。
sh.stopBalancer()Disables the balancer and waits for any in progress balancing rounds to complete.禁用平衡器并等待任何正在进行的平衡轮次完成。
sh.waitForBalancer()Internal. 内部的Waits for the balancer state to change.等待平衡器状态更改。
sh.waitForBalancerOff()Internal. 内部的Waits until the balancer stops running.等待,直到平衡器停止运行。
sh.waitForPingChange()Internal. 内部的Waits for a change in ping state from one of the mongos in the sharded cluster.等待来自分片集群中的一个mongos的ping状态的更改。
sh.updateZoneKeyRange()Associates a range of shard keys to a zone. 将一系列分片关键帧关联到一个区域。Supports configuring zones in sharded clusters.支持在分片集群中配置区域
convertShardKeyToHashed()Returns the hashed value for the input.返回输入的哈希值。

Free Monitoring免费监控

Name名称Description描述
db.enableFreeMonitoring()Enables free monitoring during runtime.在运行时启用免费监控。
db.disableFreeMonitoring()Disables free monitoring during runtime.在运行时禁用免费监视。
db.getFreeMonitoringStatus()Returns the free monitoring status.返回空闲监视状态。

Constructors构造函数

Name名称Description描述
BinData()Returns a binary data object.返回一个二进制数据对象
BulkWriteResult()Wrapper around the result set from Bulk.execute().Bulk.execute()中结果集的包装器。
Date()Creates a date object. 创建日期对象。By default creates a date object including the current date.默认情况下,创建一个包含当前日期的日期对象。
ObjectId()Returns an ObjectId.返回ObjectId
ObjectId.getTimestamp()Returns the timestamp portion of an ObjectId.返回ObjectId的时间戳部分。
ObjectId.toString()Displays the string representation of an ObjectId.显示ObjectId的字符串表示形式。
ObjectId.valueOf()Displays the str attribute of an ObjectId as a hexadecimal string.ObjectIdstr属性显示为十六进制字符串。
UUID()Converts a 32-byte hexadecimal string to the UUID BSON subtype.将32字节的十六进制字符串转换为UUID BSON子类型。
WriteResult()Wrapper around the result set from write methods.包装来自写入方法的结果集。
WriteResult.hasWriteError()Returns a boolean specifying whether the results include WriteResult.writeError.返回一个布尔值,指定结果是否包括WriteResult.writeError
WriteResult.hasWriteConcernError()Returns a boolean specifying whether whether the results include WriteResult.writeConcernError.返回一个布尔值,指定结果是否包括WriteResult.writeConcernError

Connection连接

Name名称Description描述
connect()Connects to a MongoDB instance and to a specified database on that instance.连接到MongoDB实例和该实例上的指定数据库。
Mongo()Creates a new connection object.创建新的连接对象。
Mongo.getDB()Returns a database object.返回数据库对象。
Mongo.getReadPrefMode()Returns the current read preference mode for the MongoDB connection.返回MongoDB连接的当前读取首选模式。
Mongo.getReadPrefTagSet()Returns the read preference tag set for the MongoDB connection.返回为MongoDB连接设置的读取首选项标记。
Mongo.setCausalConsistency()Enables or disables causal consistency on the connection object.启用或禁用连接对象上的因果一致性。
Mongo.setReadPref()Sets the read preference for the MongoDB connection.设置MongoDB连接的读取首选项
Mongo.startSession()Starts a session on the connection object.在连接对象上启动会话。
Mongo.watch()Opens a change stream cursor for a deployment to report on all its non-system collections across all its databases, excluding the internal admin, local, and config databases.打开部署的更改流游标,以报告其所有数据库中的所有非system集合,不包括内部admin数据库、local数据库和config数据库。
Session()The session object.会话对象。
SessionOptions()The options object for the session.会话的选项对象。

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

Note

The mongosh client-side field level encryption methods require a database connection with client-side field level encryption enabled. mongosh客户端字段级加密方法需要启用客户端字段级密码的数据库连接。If the current database connection was not initiated with client-side field level encryption enabled, either:如果当前数据库连接未在启用客户端字段级加密的情况下启动,请执行以下任一操作:

Name名称Description描述
getKeyVault()Returns the key vault object for the current MongoDB connection.返回当前MongoDB连接的键保管库对象。
KeyVault.createDataKey()An alias for KeyVault.createKey().KeyVault.createKey()的别名。
KeyVault.createKey()Creates a data encryption key for use with client-side field level encryption.创建用于客户端字段级加密的数据加密键。
KeyVault.deleteKey()Deletes the specified data encryption key from the key vault.从键保管库中删除指定的数据加密键。
KeyVault.getKey()Retrieves the specified data encryption key from the key vault.从键保管库检索指定的数据加密键。
KeyVault.getKeys()Retrieves all keys in the key vault.检索键库中的所有键。
KeyVault.addKeyAlternateName()Associates a key's alternative name to the specified data encryption key.将键的备用名称与指定的数据加密键相关联。
KeyVault.addKeyAltName()An alias for KeyVault.addKeyAlternateName().KeyVault.addKeyAlternateName()的别名。
KeyVault.removeKeyAlternateName()Removes a key's alternative name from the specified data encryption key.从指定的数据加密键中删除键的替代名称。
KeyVault.removeKeyAltName()An alias for KeyVault.removeKeyAlternateName().KeyVault.removeKeyAlternateName()的别名。
KeyVault.getKeyByAltName()Retrieves keys with the specified key alternative name.检索具有指定键替代名称的键。
KeyVault.rewrapManyDataKey()Decrypts multiple data keys and re-encrypts them.对多个数据键进行解密并重新加密。
getClientEncryption()Returns the client encryption object for supporting explicit encryption/decryption of fields.返回支持字段显式加密/解密的客户端加密对象。
ClientEncryption.createEncryptedCollection()Creates a collection with encrypted fields.创建具有加密字段的集合。
ClientEncryption.encrypt()Encrypts a field using a specified data encryption key and encryption algorithm.使用指定的数据加密键和加密算法对字段进行加密。
ClientEncryption.decrypt()Decrypts a field using the associated data encryption key and encryption algorithm.使用关联的数据加密键和加密算法对字段进行解密。

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, and require an Atlas cluster tier of at least M10.以下方法只能在MongoDB Atlas上托管的部署上运行,并且需要至少M10的Atlas集群层。

Name名称Description描述
db.collection.createSearchIndex()Creates an Atlas Search index 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索引。