I have a mongo DB document structure that follows the pattern of the Array of Ancestors (http://docs.mongodb.org/master/tutorial/model-tree-structures-with-ancestors-array/)
With this design pattern, how do I get the immediate children of a node?
A
|---|---|
| |
B D
| |
E F
So given node A, I'd like the query to return the documents at nodes B and D
In Order to find out the Immediate Children of the given Node, first you need to identify all the ancestor of the given Node.
Once you got the all the ancestors of the given node, you can easily find the Immediate children.
In the Link which you shared, below is the documents in the collection :
db.categories.insert( { _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )
db.categories.insert( { _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )
db.categories.insert( { _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Programming", ancestors: [ "Books" ], parent: "Books" } )
db.categories.insert( { _id: "Books", ancestors: [ ], parent: null } )
Say for example we need to find the Immediate children of the Node "Databases".
For that first we need to get the all ancestors of the given node "Databases".
so we can find it through below query :
var anst = db.categories.find({_id:"Databases"},{_id:0, ancestors : 1 }).toArray();
it will return us the below output :
[ { "ancestors" : [ "Books", "Programming" ] } ]
so we got to know all the ancestors of the node "Databases".
The Documents which will contain ONLY AND ALL of the node [ "Books", "Programming", "Databases" ] in the "ancestor" fields are the immediate children of the node "Databases".
To find the immediate children we can use the below query :
anst[0].ancestors.push("Databases");
db.categories.find(
{ "ancestors":
{ $all : anst[0].ancestors ,
$size: anst[0].ancestors.length
}
}
);
This will return us the below documents :
{ _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases"}
{ _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" }
Here $size is important to us, because we need ONLY those documents which have ONLY [ "Books", "Programming", "Databases" ] as there "ancestors".
Another Example :
var anst = db.categories.find({_id:"Programming"},{_id:0, ancestors : 1 }).toArray();
OutPut :
[ { "ancestors" : [ "Books" ] } ]
we can query as below :
anst[0].ancestors.push("Programming");
db.categories.find(
{ "ancestors":
{ $all : anst[0].ancestors ,
$size: anst[0].ancestors.length
}
}
);
OutPut :
{ "_id" : "Databases", "ancestors" : [ "Books", "Programming" ], "parent" : "Programming" }
{ "_id" : "Languages", "ancestors" : [ "Books", "Programming" ], "parent" : "Programming" }