aggregation framework - Recursive search on a collection in MongoDB -
i have list of documents in mongodb tree structure, model tree structures parent references pattern used. want single aggregation query returns ancestor list(till root), given 'name' property.
structure:
{ '_id': '1', 'name': 'a', 'parent': '', }, { '_id': '2', 'name': 'b', 'parent': 'a', }, { '_id': '3', 'name': 'c', 'parent': 'b', }, { '_id': '4', 'name': 'd', 'parent': 'c', }
aggregation result:(given, name = 'd')
{ '_id': '4', 'name': 'd', 'ancestors': [{name:'c'}, {name:'b'}, {name:'a'}] }
note:
can't change document structure now. cause many problems. saw many solutions suggest use model tree structures array of ancestors. cannot use now. there way achieve above pattern using single aggregation query? thank you
starting mongodb 3.4, can aggregation framework.
the first , important stage in our pipeline $graphlookup
stage. $graphlookup
allows recursively match on "parent" , "name" field. result, ancestors of each "name".
the next stage in pipeline $match
stage select "name" interested in.
the final stage $addfields
or $project
stage apply expression "ancestors" array using $map
array operator.
of course $reversearray
operator reverse our array in order expected result.
db.collection.aggregate( [ { "$graphlookup": { "from": "collection", "startwith": "$parent", "connectfromfield": "parent", "connecttofield": "name", "as": "ancestors" }}, { "$match": { "name": "d" } }, { "$addfields": { "ancestors": { "$reversearray": { "$map": { "input": "$ancestors", "as": "t", "in": { "name": "$$t.name" } } } } }} ] )
Comments
Post a Comment