当前位置:  开发笔记 > 编程语言 > 正文

$ aggregation和$查找同一个集合 - mongodb

如何解决《$aggregation和$查找同一个集合-mongodb》经验,为你挑选了1个好方法。

结构或多或少像;

[   
    {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: []}
]

childrenchildren数组不为空时,我想用名称替换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}},
])

用它的父母填充孩子,这不是我想要的:)

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

我误解了什么?



1> Shaishab Roy..:

在使用$lookup阶段之前,您应该使用$unwind儿童阵列然后$lookup儿童.在$lookup阶段之后,您需要使用$group以获取名称而不是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"]}

推荐阅读
U友50081205_653
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有