问题
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"
}
}
])
Mongo Playground
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?
回答1:
As mongoDB docs says about $lookup
:
Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing.
So no, it's not possible do it accross DBs.
But, as an addition, using Mongo exists db.getSiblingDB() option.
Docs here where says:
Used to return another database without modifying the db variable in the shell environment.
So, this is not a $lookup
but is an approach to have another Data Base data.
来源:https://stackoverflow.com/questions/65591736/how-to-populate-one-to-many-relationship-in-mongoose-with-parent-refrencing