mongo Shell Methods方法

On this page本页内容

JavaScript in MongoDB

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 specific methods, including syntax and examples, click on the specific method to go to its reference page.有关特定方法的详细信息,包括语法和示例,请单击特定方法以转到其参考页。

Collection集合

Name名称Description描述
db.collection.aggregate() Provides access to the aggregation pipeline.提供对聚合管道的访问。
db.collection.bulkWrite() Provides bulk write operation functionality.提供批量写入操作功能。
db.collection.copyTo() Deprecated.不赞成。Copies data between collections when run against MongoDB 4.0 or earlier.在MongoDB 4.0或更早版本上运行时,在集合之间复制数据。Unsupported when run against MongoDB 4.2 or later.在MongoDB 4.2或更高版本上运行时不受支持。
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.estimatedDocumentCount() Wraps count to return an approximate count of the documents in a collection or a view.包装count以返回集合或视图中文档的大致计数。
db.collection.createIndex() Builds an index on a collection.在集合上建立索引。
db.collection.createIndexes() Builds one or more indexes on a collection.在集合上生成一个或多个索引。
db.collection.dataSize() Returns the size of the collection.返回集合的大小。Wraps the size field in the output of the collStats.包装collStats输出中的size字段。
db.collection.deleteOne() Deletes a single document in a collection.删除集合中的单个文档。
db.collection.deleteMany() Deletes multiple documents in a collection.删除集合中的多个文档。
db.collection.distinct() Returns an array of documents that have distinct values for the specified field.返回指定字段具有不同值的文档数组。
db.collection.drop() Removes the specified collection from the database.从数据库中删除指定的集合。
db.collection.dropIndex() Removes a specified index on a collection.删除集合上的指定索引。
db.collection.dropIndexes() Removes all indexes on a collection.删除集合上的所有索引。
db.collection.ensureIndex() Deprecated.不赞成。Use请改用db.collection.createIndex().
db.collection.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.insert() Creates a new document in a collection.在集合中创建新文档。
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.latencyStats() Returns latency statistics for a collection.返回集合的延迟统计信息。
db.collection.mapReduce() Performs map-reduce style data aggregation.执行map reduce样式的数据聚合。
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.save() Provides a wrapper around an insert() and update() to insert new documents.insert()update()周围提供包装器以插入新文档。
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.update() Modifies a document in a collection.修改集合中的文档。
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.添加修改查询行为的特殊wire协议标志。
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 MB系统内存限制的数据。
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.将注释附加到查询,以允许在日志和system.profile集合中进行跟踪。
cursor.count() Modifies the cursor to return the number of documents in the result set rather than the documents themselves.修改光标以返回结果集中的文档数,而不是文档本身。
cursor.explain() Reports on the query execution plan for a cursor.报告游标的查询执行计划。
cursor.forEach() Applies a JavaScript function for every document in a cursor.为游标中的每个文档应用JavaScript函数。
cursor.hasNext() Returns true if the cursor has documents and can be iterated.如果游标具有文档并且可以迭代,则返回true
cursor.hint() Forces MongoDB to use a specific index for a query.强制MongoDB对查询使用特定索引。
cursor.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.cloneDatabase() Deprecated.不赞成。Copies a database from a remote host to the current host when run against MongoDB 4.0 or earlier.在MongoDB 4.0或更早版本上运行时,将数据库从远程主机复制到当前主机。Unsupported when run against MongoDB 4.2 or later.在MongoDB 4.2或更高版本上运行时不受支持。
db.commandHelp() Returns help information for a database command.返回数据库命令的帮助信息。
db.copyDatabase() Deprecated.不赞成。Copies a database to another database on the current host when run against MongoDB 4.0 or earlier.在MongoDB 4.0或更早版本上运行时,将数据库复制到当前主机上的另一个数据库。Unsupported when run against MongoDB 4.2 or later.在MongoDB 4.2或更高版本上运行时不受支持。
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.eval() Deprecated.不赞成。Passes a JavaScript function for server-side JavaScript evaluation when run against MongoDB 4.0 or earlier. Unsupported when run against MongoDB 4.2 or later.在MongoDB 4.0或更早版本上运行时,传递用于服务器端JavaScript评估的JavaScript函数。在MongoDB 4.2或更高版本上运行时不受支持。
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 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.getLastError() Checks and returns the status of the last operation.检查并返回上次操作的状态。Wraps getLastError.包装getLastError
db.getLastErrorObj() Returns the status document for the last operation.返回上次操作的状态文档。 Wraps getLastError.包装getLastError
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.getProfilingLevel() Returns the current profiling level for database operations.返回数据库操作的当前分析级别。
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.help() Displays descriptions of common db object methods.显示常用db对象方法的说明。
db.hostInfo() Returns a document with information about the system MongoDB runs on.返回一个文档,其中包含有关MongoDB运行的系统的信息。Wraps hostInfo包装hostInfo
db.isMaster() Returns a document that reports the state of the replica set.返回报告副本集状态的文档。
db.killOp() Terminates a specified operation.终止指定的操作。
db.listCommands() Displays a list of common database commands.显示常用数据库命令的列表。
db.logout() 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.printShardingStatus() Prints a report of the sharding configuration and the chunk ranges.打印分片配置和块范围的报告。
db.printSlaveReplicationInfo() Prints a report of the status of the replica set from the perspective of the secondaries.从二级副本的角度打印副本集状态的报告。
db.resetError() Deprecated.不赞成。Resets the last error status.重置最后一个错误状态。
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.无法在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.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.hint() Specifies the index to use for the update/replace operation.指定用于更新/替换操作的索引。
Bulk.find.remove() Adds a multiple document remove operation to a list of operations.将多文档删除操作添加到操作列表中。
Bulk.find.removeOne() Adds a single document remove operation to a list of operations.将单个文档删除操作添加到操作列表中。
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.返回包含Bulk()操作对象中的操作数和批数的JSON文档。
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 mongo shell user authentication/management methods.提示输入密码,以替代在各种mongo shell用户身份验证/管理方法中直接指定密码。

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 report of the status of the replica set from the perspective of the primary.从主副本的角度打印副本集状态的报告。
rs.printSlaveReplicationInfo() Prints a report of the status of the replica set 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.secondaryOk() Allows read operations on a secondary member.允许对辅助成员执行读取操作。
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.使当前的初选成为强制选举的次初选。
rs.syncFrom() Sets the member that this replica set member will sync from, overriding the default sync target selection logic.设置此复制集成员将从中同步的成员,覆盖默认同步目标选择逻辑。

Sharding分片

Name名称Description描述
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.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.disablebalancement()禁用切分收集平衡器进程,则激活该进程。
sh.disableAutoSplit() Disables auto-splitting for the sharded cluster.禁用分片群集的自动拆分。
sh.enableAutoSplit() Enables auto-splitting for the sharded cluster.启用分片群集的自动拆分。
sh.enableSharding() Enables sharding on a specific database.在特定数据库上启用分片。
sh.getBalancerHost() Deprecated since MongoDB 3.4自MongoDB 3.4以来已弃用
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.RemoveAngeFromZone()
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 boolean to report if the balancer process is currently migrating chunks.返回一个布尔值,以报告平衡器进程当前是否正在迁移块。
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.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.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.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描述
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.将ObjectId的str属性显示为十六进制字符串。
UUID() Converts a 32-byte hexadecimal string to the UUID BSON subtype.将32字节的十六进制字符串转换为UUID BSON子类型。
WriteResult() Wrapper around the result set from write methods.包装来自write方法的结果集。
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.getSecondaryOk() Indicates whether the MongoDB connection allows read operations on secondary members.指示MongoDB连接是否允许对辅助成员执行读取操作。
Mongo.isCausalConsistency() Indicates whether causal consistency is enabled on the connection object.指示是否在连接对象上启用因果一致性。
Mongo.setCausalConsistency() Enables or disables causal consistency on the connection object.启用或禁用连接对象上的因果一致性。
Mongo.setReadPref() Sets the read preference for the MongoDB connection.设置MongoDB连接的读取首选项
Mongo.setSecondaryOk() Allows read operations on secondary members 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数据库)中的所有非system集合。
Session The session object.会话对象。
SessionOptions The options object for the session.会话的选项对象。

Native原生

Name名称Description描述
cat() Returns the contents of the specified file.返回指定文件的内容。
cd() Changes the current working directory to the specified path.将当前工作目录更改为指定路径。
copyDbpath() Copies a local dbPath.复制本地dbPathFor internal use.供内部使用。
getHostName() Returns the hostname of the system running the mongo shell.返回运行mongo shell的系统的主机名。
getMemInfo() Returns a document that reports the amount of memory used by the shell.返回一个文档,该文档报告shell使用的内存量。
hostname() Returns the hostname of the system running the shell.返回运行shell的系统的主机名。
isInteractive() Returns a boolean indicating whether the mongo shell is running in interactive or script mode.返回一个布尔值,指示mongo shell是以交互模式还是脚本模式运行。
listFiles() Returns an array of documents that give the name and size of each object in the directory.返回给定目录中每个对象的名称和大小的文档数组。
load() Loads and runs a JavaScript file in the shell.在shell中加载并运行JavaScript文件。
ls() Returns a list of the files in the current directory.返回当前目录中的文件列表。
md5sumFile() The md5 hash of the specified file.指定文件的md5哈希。
mkdir() Creates a directory at the specified path.在指定的路径上创建目录。
pwd() Returns the current directory.返回当前目录。
quit() Exits the current shell session.退出当前shell会话。
removeFile() Removes the specified file from the local file system.从本地文件系统中删除指定的文件。
resetDbpath() Removes a local dbPath.删除本地dbPathFor internal use.供内部使用。
sleep() Suspends the mongo shell for a given period of time.mongo shell挂起一段给定的时间。
setVerboseShell() Configures the mongo shell to report operation timing.mongo shell配置为报告操作时间。
version() Returns the current version of the mongo shell instance.返回mongo shell实例的当前版本。
_isWindows() Returns true if the shell runs on a Windows system; false if a Unix or Linux system.如果shell在Windows系统上运行,则返回true;如果是Unix或Linux系统,则为false
_rand() Returns a random number between 0 and 1.返回一个介于01之间的随机数。

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

Note

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

  • Use the Mongo() constructor from the mongo shell to establish a connection with the required client-side field level encryption options.使用mongo shell中的Mongo()构造函数与所需的客户端字段级加密选项建立连接。The Mongo() method supports both Amazon Web Services and Local Key Management Service (KMS) providers for Customer Master Key (CMK) management.Mongo()方法支持Amazon Web服务和本地密钥管理服务(KMS)提供程序,用于客户主密钥(CMK)管理。

    or

  • Use the mongo shell command line options to establish a connection with the required options.使用mongoshell命令行选项建立与所需选项的连接。The command line options only support the AWS KMS provider for CMK management.命令行选项仅支持用于CMK管理的AWS KMS提供程序。
Name名称Description描述
getKeyVault() Returns the key vault object for the current MongoDB connection.返回当前MongoDB连接的密钥vault对象。
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() Retreives the specified data encryption key from the key vault.从密钥库中检索指定的数据加密密钥。
KeyVault.getKeys() Retrieves all keys in the key vault.检索密钥库中的所有密钥。
KeyVault.addKeyAlternateName() Associates a key alternative name to the specified data encryption key.将密钥替代名称与指定的数据加密密钥相关联。
KeyVault.removeKeyAlternateName() Removes a key alternative name from the specified data encryption key.从指定的数据加密密钥中删除密钥替代名称。
KeyVault.getKeyByAltName() Retrieves keys with the specified key alternative name.检索具有指定密钥替代名称的密钥。
getClientEncryption() Returns the client encryption object for supporting explicit encryption/decryption of 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.使用关联的数据加密密钥和加密算法解密字段。