Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json mongodb$lookup与嵌入文档有很多关联_Json_Mongodb_Has Many_Embedded Documents_Nested Documents - Fatal编程技术网

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”
那么为什么它不出现在
卡片
数组中?哦,这只是示例数据。对不起,我会修好的