定义
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
例子
You can use db.getSiblingDB() as an alternative to the use <database> helper. This is particularly useful when writing scripts using mongosh where the use helper is not available.
考虑具有两个数据库 users 和 records 的 MongoDB 实例。active 集合是users 数据库的一部分。requests 集合是records 数据库的一部分。
指定数据库
此操作将 db 对象设置为指向名为 users 的数据库,然后返回 active 集合的 document count。
db = db.getSiblingDB('users') db.active.countDocuments()
使用多个数据库
您可以创建多个引用不同数据库的 db 对象,如下列操作所示:
users = db.getSiblingDB('users') records = db.getSiblingDB('records') users.active.countDocuments() users.active.findOne() records.requests.countDocuments() records.requests.findOne()
此操作创建两个db对象。每个db对象都指向一个不同的数据库,即users或records。
对于每个数据库,该查询返回:
一个
document count和
来自该数据库中的一个集合。