Reputation: 1173
Data set with parent Child tree in MongoDB. and i need details of parent with each row. I am unable to stuff the data set as below in Mongo.
Collection Structure:
Expected Output:
Upvotes: 1
Views: 513
Reputation: 49985
You need $graphLookup to run recursive query in MongoDB. Once you get an object and all it's parents you can run $concatArrays to create one array and then use $unwind with $replaceRoot to get multiple documents in a result set:
db.collection.aggregate( [
{
$graphLookup: {
from: "collection",
startWith: "$parent_org",
connectFromField: "parent_org",
connectToField: "_id",
as: "hierarchy"
}
},
{
$match: {
_id: 4
}
},
{
$project: {
result: {
$concatArrays: [ "$hierarchy", [ { _id: "$_id", "org_name": "$org_name", parent_org: "$parent_org" } ] ]
}
}
},
{
$unwind: "$result"
},
{
$replaceRoot: {
newRoot: "$result"
}
},
{
$sort: {
_id: 1
}
}
])
Upvotes: 1