I have three collections: parent, child1, child2.
parent collection:
[{_id:1}, {_id:2}, {_id:3}]
child1 collection:
[{_id:1, child1:'a', parent:1}, {_id:2, child1:'b', parent:1}, {_id:3, child1:'c', parent:2}]
child2 collection:
[{_id:1, child1:'d', parent:2}, {_id:2, child1:'e', parent:3}]
collections child1 and child2 referenced to parent collection.
now, I want a query in mongoose to get a result like this:
[
{
_id:1,
child1:[{_id:1, child1:'a'}, {_id:2, child1:'b'}],
child2:[],
},
{
_id:2,
child1:[{_id:2, child1:'c'}],
child2:[{_id:1, child1:'d'}],
},
{
_id:3,
child1:[],
child2:[{_id:2, child1:'e'}],
},
]
my try in Aggregate is work correctly:
db.parent.aggregate([
{
"$lookup": {
"from": "child1",
"localField": "_id",
"foreignField": "parent",
"as": "child1"
}
},
{
"$lookup": {
"from": "child2",
"localField": "_id",
"foreignField": "parent",
"as": "child2"
}
}
])
This works when the collections are in the same database but my collections in the separate database.
e.g: parent collection in parent database and child1 and child2 collections in child database.
Do you have any idea for use aggregation across multiple databases or how can I use populate to solve this problem?