I'm trying to filter child documents from a MongoDB collection. Along with the child documents trying to fetch corresponding immediate parent documents as well.
**My parent document:**
{ "id":"123", "source":"02", "child":{"id":"456"}}
**My child document:**
{ "id":"456", "source":"01", "parent":{"id":"123"}}
How to fetch the child documents along with its corresponding parent documents dynamically?
You can utilise $lookup aggregation pipeline stage to perform a left outer join to the same collection (unsharded). Given your example documents, to retrieve children of parent document(s):
db.collectionA.aggregate([
{"$match": {"child": {"$exists": 1} } },
{"$lookup":{
"from": "collectionA",
"localField": "id",
"foreignField": "parent.id",
"as": "children"}
}
]);
To retrieve parent from child document(s):
db.collectionA.aggregate([
{"$match": {"parent": {"$exists": 1} } },
{"$lookup":{
"from": "collectionA",
"localField": "id",
"foreignField": "child.id",
"as": "parent"}
}
]);
I'd also recommend reviewing MongoDB Model Tree Structures, especially: