Definition定义
db.getSiblingDB(<database>)-
Parameter参数Type类型Description描述databasestring字符串The name of a MongoDB database.MongoDB数据库的名称。Returns:返回A database object.数据库对象。Used to return another database without modifying the用于在不修改shell环境中的dbvariable in the shell environment.db变量的情况下返回另一个数据库。
Compatibility兼容性
This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:
- MongoDB Atlas
: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
Note
This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令。
- MongoDB Enterprise
: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本 - MongoDB Community
: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本
Example示例
You can use 您可以使用db.getSiblingDB() as an alternative to the use <database> helper. db.getSiblingDB()作为use <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. The requests collection is a part of the records database.active集合是users数据库的一部分。requests集合是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. Each db object refers to a different database, users or records.db对象。每个db对象都引用不同的数据库、users或records。
For each database, the query returns:对于每个数据库,查询返回:
a文档计数,以及document count, andan某个示例文档example document
from a collection in that database.来自该数据库中的集合。