Is it possible to get the result like above using my current version of mongo. If so can anyone help me how can i achieve this result?
Hi Soorya,
As of MongoDB v3.0, there is no operator in the aggregation framework that would be able to nest the documents from the same collection. I would suggest to write a script to achieve the result as you have described.
A simple MongoDB JavaScript example for a fixed depth levels of 2 would be:
/* For each document in the collection */
db.collection.find({}).forEach(function(doc){
var children = [];
/* For each child in the children field */
doc.children.forEach(function(key){
var tmp = db.collection.findOne({_id:key});
children.push(tmp);
});
/* Substitute children field with the newly constructed children field */
doc.children = children;
/* Only print document with children */
if(children.length > 0) printjson(doc);
});
You would need a recursive function if the levels depth is unknown.
There are a number of example patterns in MongoDB documentation to Model Tree Structures that you might find useful. i.e. data model referencing.
Regards,
Wan.