【问题标题】:mongodb $lookup has_many association from embedded document来自嵌入式文档的 mongodb $lookup has_many 关联
【发布时间】:2020-10-26 20:03:06
【问题描述】:

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

{
    _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 来获得我想要的结果,但我无法让它工作

【问题讨论】:

  • 如果你使用foreignField: "list_id" 那么为什么cards 数组中没有它?
  • 哦,这只是示例数据。抱歉,我会解决的

标签: json mongodb has-many embedded-documents nested-documents


【解决方案1】:

您需要一个额外的聚合管道步骤来“合并”这两个列表,您可以通过运行 $map 和嵌入的 $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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2020-12-29
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多