Json mongodb$lookup与嵌入文档有很多关联
我有一个图板收藏,一个列表收藏和一个卡片收藏。一组列表嵌入在董事会文档中。我正在尝试获得如下输出:Json mongodb$lookup与嵌入文档有很多关联,json,mongodb,has-many,embedded-documents,nested-documents,Json,Mongodb,Has Many,Embedded Documents,Nested Documents,我有一个图板收藏,一个列表收藏和一个卡片收藏。一组列表嵌入在董事会文档中。我正在尝试获得如下输出: { _id: 1, title: "a board", lists: [ { _id: 1, title: "a list", cards: [ { _id: 1, title: "a card", list_id: 1 }, { _id: 2, t
{
_id: 1,
title: "a board",
lists: [
{
_id: 1,
title: "a list",
cards: [ { _id: 1, title: "a card", list_id: 1 }, { _id: 2, title: "another card", list_id: 1 } ]
},
...
]
}
我想把这些卡片嵌套在它所属的列表中。卡片文档有一个列表\u id
字段。我试过这个:
db.boards.aggregate([
{ '$match' => { _id: 1 } },
{ '$lookup' => {
from: "cards",
localField: "lists._id",
foreignField: "list_id",
as: "cards"
} },
])
但结果是:
{
_id: 1,
title: "a board",
lists: [ { _id: 1, title: "a list" } ],
cards: [ { _id: 1, title: "a card", list_id: 1 }, { _id: 2, title: "another card", list_id: 1 } ]
}
我知道我必须使用
$unwind
来获得我想要的结果,但我无法让它工作您需要一个额外的聚合管道步骤来“合并”这两个列表,您可以通过运行embedded来实现。它只是在两个阵列上执行“连接”操作:
{
$project: {
_id: 1,
title: 1,
lists: {
$map: {
input: "$lists",
as: "list",
in: {
$mergeObjects: [
"$$list",
{
cards: {
$filter: {
input: "$cards",
cond: { $eq: [ "$$this.list_id", "$$list._id" ] }
}
}
}
]
}
}
}
}
}
如果您使用
foreignField:“list_id”
那么为什么它不出现在卡片数组中?哦,这只是示例数据。对不起,我会修好的