JERRY
JERRY

Reputation: 1173

Recursive query in Mongodb

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:

enter image description here

Expected Output:

enter image description here

Upvotes: 1

Views: 513

Answers (1)

mickl
mickl

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
        }
    }
])

Mongo Playground

Upvotes: 1

Related Questions