mongodb $lookup has_many 来自嵌入文档的关联

mongodb $lookup has_many association from embedded document

我有一个看板集合、一个列表集合和一个卡片集合。一组列表嵌入在董事会文件中。我正在尝试获得如下所示的输出:

{
    _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 } ] 
      },
      ...
    ]
  }

我想将卡片嵌套在它所属的列表中。卡片文档有一个 list_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 来获得我想要的结果,但我无法让它工作

您需要一个额外的聚合管道步骤来“合并”这两个列表,您可以通过 运行 $map with embedded $filter 实现。它只是对两个数组的“连接”操作:

{
    $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" ] }
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}

Mongo Playground