0

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

{
    _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才能获得我想要的结果,但我无法让它发挥作用

4

1 回答 1

1

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

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

蒙戈游乐场

于 2020-07-06T18:46:22.337 回答