On this page本页内容
You can use 您可以使用db.getSiblingDB() as an alternative to the use <database> helper. db.getSiblingDB()作为使用<database>助手的替代方法。This is particularly useful when writing scripts using 这在使用mongosh where the use helper is not available.mongosh编写脚本时尤其有用,因为use帮助程序不可用。
Consider a MongoDB instance with two databases, 考虑一个包含两个数据库、users and records. users和records的MongoDB实例。The active collection is a part of the users database. active集合是users数据库的一部分。The 请求集合是requests collection is a part of the records database.records数据库的一部分。
This operation sets the 此操作将db object to point to the database named users, and then returns a document count for the active collection.db对象设置为指向名为users的数据库,然后返回active集合的文档计数。
db = db.getSiblingDB('users')
db.active.countDocuments()
You can create multiple 您可以创建多个db objects, that refer to different databases, as in the following sequence of operations:db对象,这些对象引用不同的数据库,如下操作顺序所示:
users = db.getSiblingDB('users') records = db.getSiblingDB('records') users.active.countDocuments() users.active.findOne() records.requests.countDocuments() records.requests.findOne()
This operation creates two 此操作创建两个db objects. db对象。Each 每个db object refers to a different database, users or records.db对象引用不同的数据库、users或records。
For each database, the query returns:对于每个数据库,查询返回:
document count, andexample documentfrom a collection in that database.来自该数据库中的集合。