Database Manual / Reference

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.有关特定方法的详细信息,包括语法和示例,请单击该方法参考页面的链接。

MongoDB Search Index MethodsMongoDB搜索索引方法

MongoDB Search indexes let you query data in MongoDB Search, while Vector Search indexes let you query data in Vector Search. MongoDB搜索索引允许您在MongoDB搜索中查询数据,而矢量搜索索引则允许您在矢量搜索中查询。MongoDB Search and Vector Search indexes enable performant text search queries by mapping search terms to the documents that contain those terms.MongoDB搜索和矢量搜索索引通过将搜索词映射到包含这些词的文档,实现了高性能的文本搜索查询。

Use the following methods to manage MongoDB Search and Vector Search indexes.使用以下方法管理MongoDB搜索和矢量搜索索引。

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

Atlas Stream Processing MethodsAtlas流处理方法

Atlas Stream ProcessorsAtlas流处理器 let you perform aggregation operations against streams of continuous data using the same data model and query API that you use with at-rest data.允许您使用与静态数据相同的数据模型和查询API对连续数据流执行聚合操作。

Use the following methods to manage Stream Processors:使用以下方法管理流处理器:

Important

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

Name名称Description描述
sp.createStreamProcessor()Creates a stream processor.创建流处理器。
sp.listStreamProcessors()Lists all existing stream processors on the current stream processing instance.列出当前流处理实例上的所有现有流处理器。
sp.process()Creates an ephemeral stream processor.创建临时流处理器。
sp.processor.drop()Deletes an existing stream processor.删除现有的流处理器。
sp.processor.sample()Returns an array of sampled results from a currently running stream processor.返回当前运行的流处理器的采样结果数组。
sp.processor.start()Starts an existing stream processor.启动现有的流处理器。
sp.processor.stats()Returns statistics summarizing an existing stream processor.返回总结现有流处理器的统计信息。
sp.processor.stop()Stops a currently running stream processor.停止当前正在运行的流处理器。

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.返回集合的大小。将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.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 an in-memory sort operation.允许MongoDB在处理内存排序操作时使用磁盘上的临时文件来存储超过100 MB系统内存限制的数据。
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.返回一个集合或视图对象。用于访问名称在蒙古语中无效的集合。
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对象方法的描述。
db.hostInfo()Returns a document with information about the system MongoDB runs on. Wraps hostInfo返回一个包含MongoDB运行系统信息的文档。包装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.rotateCertificates()Performs online TLS certificate rotation. Wraps rotateCertificates.执行在线TLS证书轮换。包装rotateCertificates(旋转证书)。
db.runCommand()Runs a database command.运行数据库命令
db.serverBuildInfo()Returns a document that displays the compilation parameters for the mongod instance. Wraps buildInfo.返回一个文档,显示mongod实例的编译参数。包装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. 打开数据库的更改流游标,以报告其所有非系统集合。Cannot be opened on the admin, local or config databases.无法在adminlocalconfig数据库上打开。

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 plan cache query shape. 清除指定计划缓存查询形状的缓存查询计划。Accessible through the plan cache object of a specific collection, i.e. 可通过特定集合的计划缓存对象访问,即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()

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()操作生成器。
Mongo.bulkWrite()Executes bulk write operations on multiple namespaces.对多个命名空间执行批量写入操作。
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.阻止当前成员在一段时间内寻求primary。
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.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描述
convertShardKeyToHashed()Returns the hashed value for the input.返回输入的哈希值。
db.checkMetadataConsistency()

Checks the cluster or database for inconsistent sharding metadata.检查群集或数据库是否存在不一致的分片元数据。

New in version 7.0.在版本7.0中新增。

db.collection.checkMetadataConsistency()

Checks the collection for inconsistent sharding metadata.检查集合中是否存在不一致的分片元数据。

New in version 7.0.在版本7.0中新增。

sh.abortMoveCollection()

Stops an in-progress moveCollection operation.停止正在进行的moveCollection操作。

New in version 8.0.在版本8.0中新增。

sh.abortReshardCollection()

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

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

sh.addShard()Adds a shard to a sharded cluster.分片添加到分片集群。
sh.addShardTag()This method aliases to sh.addShardToZone().此方法是sh.addShardToZone()的别名。
sh.addShardToZone()Associates a shard to a zone. Supports configuring zones in sharded clusters.将一个分片与一个区域相关联。支持在分片集群中配置区域
sh.addTagRange()This method aliases to sh.updateZoneKeyRange().此方法别名为sh.updateZoneKeyRange()
sh.balancerCollectionStatus()Returns information on whether the chunks of a sharded collection are balanced.返回有关分片集合的块是否平衡的信息。
sh.checkMetadataConsistency()

Checks the cluster for inconsistent sharding metadata.检查集群中是否存在不一致的分片元数据。

New in version 7.0.在版本7.0中新增。

sh.commitReshardCollection()

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

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

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.0.3, automatic chunk splitting is not performed. This is because of balancing policy improvements. Auto-splitting commands still exist, but do not perform an operation.从MongoDB 6.0.3开始,不执行自动块分割。这是因为平衡了政策的改进。自动拆分命令仍然存在,但不执行操作。

sh.disableBalancing()Disable 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.启用分片群集的自动拆分。

Starting in MongoDB 6.0.3, automatic chunk splitting is not performed. This is because of balancing policy improvements. Auto-splitting commands still exist, but do not perform an operation.从MongoDB 6.0.3开始,不执行自动块分割。这是因为平衡了政策的改进。自动拆分命令仍然存在,但不执行操作。

sh.enableBalancing()Activates the sharded collection balancer process if previously disabled using sh.disableBalancing().如果之前使用sh.disableBalancing()禁用了分片集合平衡器进程,则激活该进程。
sh.enableSharding()Creates a 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.sh.getShardedDataDistribution()$shardedDataDistribution聚合管道阶段的shell辅助方法。
sh.help()Returns help text for the sh methods.返回sh方法的帮助文本。
sh.isBalancerRunning()Returns a document describing the status of the balancer.返回一个描述平衡器状态的文档。
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.迁移分片集群中的
sh.moveCollection()Moves a single unsharded collection to a different shard.将单个未分片集合移动到其他分片。
sh.moveRange()Move ranges between shards.在分片之间移动范围。
sh.removeRangeFromZone()Removes an association between a range of shard keys and a zone. Supports configuring zones in sharded clusters.删除一系列分片键和区域之间的关联。支持在分片集群中配置区域
sh.removeShardTag()This method aliases to sh.removeShardFromZone().此方法别名为sh.removeShardFromZone()
sh.removeShardFromZone()Removes the association between a shard and a zone. Use to manage zone sharding.删除分片和区域之间的关联。用于管理区域分片
sh.removeTagRange()This method aliases to sh.removeRangeFromZone().此方法别名为sh.removeRangeFromZone()
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.shardAndDistributeCollection()

Shards a collection and immediately redistributes the data using the provided shard key.对集合进行分片,并立即使用提供的分片键重新分发数据。

New in version 8.0.在版本8.0中新增。

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.unshardCollection()

Unshards an existing sharded collection and moves the collection data onto a single shard. When you unshard a collection, the collection cannot be partitioned across multiple shards and the shard key is removed.解开现有的分片集合,并将集合数据移动到单个分片上。当您取消对集合的分区时,该集合不能跨多个分片进行分区,并且分片键将被删除。

New in version 8.0.在版本8.0中新增。

sh.updateZoneKeyRange()Associates a range of shard keys to a zone. Supports configuring zones in sharded clusters.将一系列分片键与一个区域相关联。支持在分片集群中配置区域
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状态发生变化。

Constructors构造函数

Name名称Description描述
Binary.createFromBase64()Creates a binary object from a base64 value.从base64值创建二进制对象。
Binary.createFromHexString()Creates a binary object from a hexadecimal value.从十六进制值创建二进制对象。
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.创建日期对象。默认情况下,创建一个包含当前日期的日期对象。
HexData()Returns a binary data object.返回一个二进制数据对象
ObjectId()Returns an ObjectId.返回一个ObjectId
ObjectId.createFromBase64()Creates an ObjectId from a base64 value.从base64值创建ObjectId
ObjectId.createFromHexString()Creates an ObjectId from a hexadecimal value.从十六进制值创建ObjectId
ObjectId.getTimestamp()Returns the timestamp portion of an ObjectId.返回ObjectId的时间戳部分。
ObjectId.toString()Displays the string representation of an ObjectId.显示ObjectId的字符串表示形式。
UUID() (mongosh method)Converts a 32-byte hexadecimal string to the UUID BSON subtype.将32字节的十六进制字符串转换为UUID BSON子类型。
WriteResult()Wrapper around the result set from write methods.围绕写入方法的结果集进行包装。

Connection连接

Name名称Description描述
connect() (mongosh method)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.打开部署的更改流游标,以报告其所有数据库中的所有非系统集合,不包括内部adminlocalconfig数据库。
Session()The session object.会话对象。
SessionOptions()The options object for the session.会话的选项对象。

In-Use Encryption使用中的加密

MongoDB supports two approaches to In-Use Encryption, Client-Side Field Level Encryption (CSFLE) and Queryable Encryption (QE). MongoDB支持两种使用中加密方法,客户端字段级加密(CSFLE)和可查询加密(QE)。ClientEncryption is an abstraction used across drivers and mongosh that encapsulates operations for both CSFLE and QE. 是跨驱动程序和mongosh使用的抽象,它封装了CSFLE和QE的操作。However, some methods are specific to one feature.然而,有些方法是特定于一个特征的。

Note

The mongosh ClientEncryption methods require a database connection with in-use encryption enabled. If the current database connection was not initiated with in-use encryption enabled, either:mongosh ClientEncryption方法需要启用正在使用的加密的数据库连接。如果当前数据库连接不是在启用使用中的加密的情况下启动的,则:

Commands with aliases are grouped together.带有别名的命令被组合在一起。

Name名称CSFLEQEDescription描述
getKeyVault()Returns the key vault object for the current MongoDB connection.返回当前MongoDB连接的键保管库对象。
KeyVault.createKey()
KeyVault.createDataKey()
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()
KeyVault.addKeyAltName()
Associates a key alternative name to the specified data encryption key.将键备选名称与指定的数据加密键相关联。
KeyVault.removeKeyAlternateName()
KeyVault.removeKeyAltName()
Removes a key alternative name from the specified data encryption key.从指定的数据加密键中删除键备选名称。
KeyVault.getKeyByAltName()Retrieves keys with the specified key alternative name.使用指定的键替代名称检索键。
KeyVault.rewrapManyDataKey()Decrypts multiple data keys and re-encrypts them with a new master key.解密多个数据键,并用新的主键重新加密。
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.encryptExpression()Encrypts a query expression using a specified data encryption key and encryption options.使用指定的数据加密键和加密选项加密查询表达式。
ClientEncryption.decrypt()Decrypts a field using the associated data encryption key and encryption algorithm.使用关联的数据加密键和加密算法解密字段。