db.getSiblingDB()

On this page本页内容

Definition定义

db.getSiblingDB(<database>)
Parameter参数Type类型Description描述
databasestringThe name of a MongoDB database.MongoDB数据库的名称。
Returns:返回:A database object.数据库对象。

Used to return another database without modifying the db variable in the shell environment.用于返回另一个数据库,而不修改shell环境中的db变量。

Example示例

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. 考虑一个包含两个数据库、usersrecords的MongoDB实例。The active collection is a part of the users database. active集合是users数据库的一部分。The requests collection is a part of the records database.请求集合是records数据库的一部分。

Specify a Database指定数据库

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

Use Multiple Databases使用多个数据库

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对象引用不同的数据库、usersrecords

For each database, the query returns:对于每个数据库,查询返回:

from a collection in that database.来自该数据库中的集合。

←  db.getReplicationInfo()db.hello() →