$aggregation 和 $look up 在同一个集合中 - mongodb

$aggregation and $look up in the same collection- mongodb

结构差不多;

[   
    {id: 1, name: "alex" , children: [2, 4, 5]},
    {id: 2, name: "felix", children: []},
    {id: 3, name: "kelly", children: []},
    {id: 4, name: "hannah", children: []},
    {id: 5, name: "sonny", children: [6]},
    {id: 6, name: "vincenzo", children: []}
]

children 数组不为空时,我想用名称替换 children id。

所以查询结果预计为;

[   {id: 1, name: "alex" , children: ["felix", "hannah" , "sonny"]}
    {id: 5, name: "sonny", children: ["vincenzo"]}
]

我做了什么来实现这个目标;

db.list.aggregate([
  {$lookup: { from: "list", localField: "id", foreignField: "children", as: "children" }},
  {$project: {"_id" : 0, "name" : 1, "children.name" : 1}},
])

用 parent 填充 children,这不是我想要的 :)

{ "name" : "alex", "parent" : [ ] }
{ "name" : "felix", "parent" : [ { "name" : "alex" } ] }
{ "name" : "kelly", "parent" : [ ] }
{ "name" : "hannah", "parent" : [ { "name" : "alex" } ] }
{ "name" : "sonny", "parent" : [ { "name" : "alex" } ] }
{ "name" : "vincenzo", "parent" : [ { "name" : "sonny" } ] }

我误会了什么?

在使用 $lookup 阶段之前,您应该对子数组使用 $unwind,然后对子数组使用 $lookup。在 $lookup 阶段之后,您需要使用 $group 来获取带有 name 而不是 id

的子数组

你可以试试:

db.list.aggregate([
    {$unwind:"$children"},
    {$lookup: { 
        from: "list",
        localField: "children",
        foreignField: "id",
        as: "childrenInfo" 
      }
    },
    {$group:{
       _id:"$_id",
       children:{$addToSet:{$arrayElemAt:["$childrenInfo.name",0]}},
       name:{$first:"$name"}
      }
    }
]);

// can use $push instead of $addToSet if name can be duplicate

为什么用$group

例如: 你的第一份文件

{id: 1, name: "alex" , children: [2, 4, 5]}

$unwind 之后,您的文档将看起来像

{id: 1, name: "alex" , children: 2},
{id: 1, name: "alex" , children: 4},
{id: 1, name: "alex" , children: 5}

$lookup

之后
{id: 1, name: "alex" , children: 2,
  "childrenInfo" : [ 
        {
            "id" : 2,
            "name" : "felix",
            "children" : []
        }
    ]},
//....

然后在 $group

之后
 {id: 1, name: "alex" , children: ["felix", "hannah" , "sonny"]}

在当前的 Mongo 3.4 版本中,您可以使用 $graphLookup

$maxDepth 设置为 0 用于非递归查找。您可能希望在查找之前添加一个 $match 阶段以过滤没有子项的记录。

db.list.aggregate([{
    $graphLookup: {
        from: "list",
        startWith: "$children",
        connectFromField: "children",
        connectToField: "id",
        as: "childrens",
        maxDepth: 0,
    }
}, {
    $project: {
        "_id": 0,
        "name": 1,
        "childrenNames": "$childrens.name"
    }
}]);