I have a list of documents in MongoDB with tree structure, where Model Tree Structures with Parent References pattern used. I want a single aggregation query which returns a
If you are open to use client side javascript, you can use recursion on the mongo shell to achieve this:
var pushAncesstors = function (name, doc) {
if(doc.parent) {
db.collection.update({name : name}, {$addToSet : {"ancesstors" : {name : doc.parent}}});
pushAncesstors(name, db.collection.findOne({name : doc.parent}))
}
}
db.collection.find().forEach(function (doc){
pushAncesstors(doc.name, doc);
})
This will give you complete hirearchy for all products. Sample output:
{ "_id" : "1", "name" : "A", "parent" : "" }
{ "_id" : "2", "name" : "B", "parent" : "A", "ancesstors" : [ { "name" : "A" } ] }
{ "_id" : "3", "name" : "C", "parent" : "B", "ancesstors" : [ { "name" : "B" }, { "name" : "A" } ] }
{ "_id" : "4", "name" : "D", "parent" : "C", "ancesstors" : [ { "name" : "C" }, { "name" : "B" }, { "name" : "A" } ] }
If your requirement is not to update the correct collection, insert the data in a diffferent collection and update there. The pushAncesstors
function will change to:
var pushAncesstors = function (name, doc) {
if(doc.parent) {
db.outputColl.save(doc)
db.outputColl.update({name : name}, {$addToSet : {"ancesstors" : {name : doc.parent}}});
pushAncesstors(name, db.collection.findOne({name : doc.parent}))
}
}