【发布时间】:2018-05-16 04:13:24
【问题描述】:
我正在寻求帮助。
我有一个名为“business”的集合,其中有这样的对象:
[{
"_id": ObjectId("5aefa97166763d28fc984c7a"),
"name": "Business 1",
"boxes": [
{
"_id": ObjectId("5ac6bb69f3c36e17f0d34bd2")
}
]
}]
还有一个名为 box 的集合,它的对象如下:
[{
_id: ObjectId("5ac6bb69f3c36e17f0d34bd2"),
name:"Box1",
color:"blue"
}]
这里的想法是有些企业拥有盒子,我希望将这两个收藏分开。
也就是说,我想检索这个结果:
[{
"_id": ObjectId("5aefa97166763d28fc984c7a"),
"name": "Business 1",
"boxes": [{
_id: ObjectId("5ac6bb69f3c36e17f0d34bd2"),
name:"Box1",
color:"blue"
}]
}]
但我得到了这个结果:
[{
"_id": ObjectId("5aefa97166763d28fc984c7a"),
"name": "Business 1",
"boxes": [
{
"_id": ObjectId("5ac6bb69f3c36e17f0d34bd2")
}
]
}]
使用 $lookup 如下所示:
db.db('database').collection("business").aggregate({
$lookup:{
from: "boxes",
localField: "_id",
foreignField: "_id",
as: "box"
},
"$unwind": "$boxes"
}).toArray(function(err, result) {
if (err) throw err;
res.send(result);
db.close();
res.end();
});
我做错了什么?
谢谢大家!
【问题讨论】:
-
localField: 'boxes._id'你指向了错误的路径。此外,您不需要$unwind来获得所需的结果,只需使用as: 'boxes'用您的外部集合匹配覆盖ObjectId值数组。无论如何,$unwind是管道中的一个单独文档,但只需删除该行,因为它当前的语法不正确且不需要。
标签: mongodb aggregate lookup ref