我的MongoDB中有两个主要集合,users&住址我在第一个集合(用户)中使用"$ref"和"$id"来引用第二个集合(地址)的文档。我想写一个查询来显示用户及其地址的详细信息。
这是我的第一个"用户"集合。它有1个文档
{
"_id" : ObjectId("52ffc33cd85242f436000001"),
"contact" : "987654321",
"dob" : "01-01-1991",
"name" : "Tom Benzamin",
"address" : [
{
"$ref" : "address",
"$id" : ObjectId("534009e4d852427820000002"),
"$db" : "test"
},
{
"$ref" : "address",
"$id" : ObjectId("52ffc4a5d85242602e000000"),
"$db" : "test"
}
]
}
这是我的第二个收藏"地址"。它有3个文件
{
"_id" : ObjectId("52ffc4a5d85242602e000000"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456.0000000000000000,
"city" : "Los Angeles",
"state" : "California"
},
{
"_id" : ObjectId("52ffc4a5d85242602e000001"),
"building" : "170 A, Acropolis Apt",
"pincode" : 456789.0000000000000000,
"city" : "Chicago",
"state" : "Illinois"
},
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456.0000000000000000,
"city" : "Los Angeles",
"state" : "California"
}
我已经写了这个代码,但它不起作用。当我运行时,它显示单词"null"
var user = db.users.findOne({"name":"Tom Benzamin"})
var dbRef = user.address
db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
它显示为null,因为dbRef是一个数组:
{
"0" : {
"$ref" : "address",
"$id" : ObjectId("52ffc4a5d85242602e000000"),
"$db" : "test"
},
"1" : {
"$ref" : "address",
"$id" : ObjectId("534009e4d852427820000002"),
"$db" : "test"
}
}
试试这个:
var user = db.users.findOne({"name":"Tom Benzamin"})
var dbRef = user.address
var ids = new Array();
for (i = 0; i < dbRef.length; i++){
ids.push(dbRef[i].$id)
}
db[dbRef[0].$ref].find({"_id":{$in:ids}});