I need to flatten my parent child collection in mongodb . This is similar to question asked for sql at :
Flatten parent child hierarchy with multiple parents
my collection is like category: {_id, type, name, parent:(mapped to self i.e. category collection) )}
And the current depth of child is 3 with type L1, L2,L3
Result will be with fields: (L1_id, L1_name, L2_id, L2_name, L3_id, L3_name)
Kindly help
You can use mongodb aggregation pipeline
to achieve the same. More specifically you can use $lookup
twice to populate parent
and its parent
, and finally $project
to flatten the structure.
Try this:
Category.aggregation([{
$lookup : {
from :"categories",
localField : "parent",
foreignField : "_id",
as :"parent"
}
},{
$unwind : "$parent"
},{
$lookup : {
from :"categories",
localField : "parent.parent",
foreignField : "_id",
as :"parent.parent"
}
},{
$unwind : "$parent.parent"
},{
$project : {
l1_id : "$_id",
l1_name : "$name",
l2_id : "$parent._id",
l2_name : "$parent.name" ,
l3_id : "$parent.parent._id",
l2_name : "$parent.parent.name"
}
}]).then(result => {
// result will have l1_id, l1_name, l2_id, l2_name, l3_id, l3_name
// where l2 is the parent,
// and l3 is the parent of parent
}).
Note: $unwind
is used after $lookup
stage, as $lookup
returns an array, we need to unwind it to convert it to object.
For more info please read Mongodb $lookup documentation,and $project documentation.
i hope this helps you out.