$ aggregation and $ look in the same collection-mongodb

The structure is more or less similar;

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

I want to replace childrenid with names when the array is childrennot empty.

Thus, the query result is expected as:

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

What have I done for this

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

filled with children with a parent, which is not what I want :)

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

What did I misunderstand?

+4
source share
2 answers

Before you use the stage $lookup, you must use $unwindfor the children’s array, then $lookupfor the children. After the stage $lookupyou need to use $groupto get a child array with a name instead of id

You can try:

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"]}
+6

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"
    }
}]);
+3

Source: https://habr.com/ru/post/1666493/


All Articles