从Data Types个文档中:
与遗留的mongoshell 相比,MongoDB Shell(mongosh
)的类型处理更符合MongoDB驱动程序使用的默认类型.
例如,NODE-MongoDB-DRIVER中5.6/classes/BSON.DBRef.html#constructor类的构造函数签名:
new DBRef(collection: string, oid: ObjectId, db?: string, fields?: Document): DBRef
属性:
name |
type |
description |
collection |
string |
the collection name. |
oid |
ObjectId |
the reference ObjectId. |
db |
string |
optional db name, if omitted the reference is local to the current db. |
user.address
是DBRef
类的实例:
Atlas atlas-zy5qpa-shard-0 [primary] test> user.address instanceof DBRef
true
因此,mongosh
中的命令应该是:
Atlas atlas-zy5qpa-shard-0 [primary] test> db[user.address.collection].findOne({_id: user.address.oid})
{
_id: ObjectId("534009e4d852427820000002"),
building: '22 A, Indiana Apt',
pincode: 123456,
city: 'Los Angeles',
state: 'California'
}
或者,使用toJSON()方法获取BSON.DBRefLike数据.
Atlas atlas-zy5qpa-shard-0 [primary] test> dbRef.toJSON()
{
'$ref': 'address_home',
'$id': ObjectId("534009e4d852427820000002"),
'$db': 'test'
}
Atlas atlas-zy5qpa-shard-0 [primary] test> db[dbRef.toJSON().$ref].findOne({_id: dbRef.toJSON().$id})
{
_id: ObjectId("534009e4d852427820000002"),
building: '22 A, Indiana Apt',
pincode: 123456,
city: 'Los Angeles',
state: 'California'
}
用户文档(Note: I use 100 database, not 101):
Atlas atlas-zy5qpa-shard-0 [primary] test> db.users.findOne({name: 'Tom Benzamin'})
{
_id: ObjectId("53402597d852426020000002"),
address: DBRef("address_home", ObjectId("534009e4d852427820000002"), "test"),
contact: '987654321',
dob: '01-01-1991',
name: 'Tom Benzamin'
}
mongosh
版本:
$ mongosh --version
1.10.1
MongoDB版本:
Atlas atlas-zy5qpa-shard-0 [primary] test> db.version()
6.0.6
附注:tutorialspoint站点的文档中甚至没有MongoDB和mongosh
版本的信息.我想我不会用它了.