简体   繁体   English

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

[英]mongodb $lookup has_many association from embedded document

I have a boards collection, a lists collection, and a cards collection.我有一个板集合、一个列表集合和一个卡片集合。 An array of lists is embedded in a board document.列表数组嵌入在板文档中。 I am trying to get an output that looks like this:我正在尝试获得一个看起来像这样的 output:

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

I want to nest the cards in the list it belongs to.我想将卡片嵌套在它所属的列表中。 The card document has a list_id field.卡片文档有一个list_id字段。 I tried this:我试过这个:

db.boards.aggregate([
  { '$match' => { _id: 1 } },
  { '$lookup' => {
    from: "cards",
    localField: "lists._id",
    foreignField: "list_id",
    as: "cards"
  } },
])

But that resulted in:但这导致:

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

I know that I have to use $unwind to get the result I want, but I can't get it to work我知道我必须使用$unwind来获得我想要的结果,但我无法让它工作

You need one additional aggregation pipeline step to "merge" these two lists and you can achieve it by running $map with embedded $filter .您需要一个额外的聚合管道步骤来“合并”这两个列表,您可以通过运行带有嵌入式$filter$map来实现它。 It simply works as a "join" operation on two arrays:它只是作为两个 arrays 上的“加入”操作:

{
    $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蒙戈游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM