我有三个集合:parent、child1、child2。
父集合:
[{_id:1}, {_id:2}, {_id:3}]
child1 集合:
[{_id:1, child1:'a', parent:1}, {_id:2, child1:'b', parent:1}, {_id:3, child1:'c', parent:2}]
child2 集合:
[{_id:1, child1:'d', parent:2}, {_id:2, child1:'e', parent:3}]
<块引用>
集合 child1 和 child2 引用父集合。
现在,我想在 mongoose 中进行查询以获得如下结果:
[
{
_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'}],
},
]
我在 Aggregate 中的尝试工作正常:
db.parent.aggregate([
{
"$lookup": {
"from": "child1",
"localField": "_id",
"foreignField": "parent",
"as": "child1"
}
},
{
"$lookup": {
"from": "child2",
"localField": "_id",
"foreignField": "parent",
"as": "child2"
}
}
])
当集合在同一个数据库中但我的集合在单独的数据库中时,这有效。
<块引用>例如:父数据库中的父集合和子数据库中的 child1 和 child2 集合。
您对跨多个数据库使用聚合有什么想法,或者我如何使用 populate 来解决这个问题?
答案 0 :(得分:0)
正如 mongoDB docs 所说的关于 $lookup
:
对相同数据库中的未分片集合执行左外部联接,以从“联接”集合中过滤文档以进行处理。
所以不,不可能跨数据库这样做。
但是,作为补充,使用 Mongo 存在 db.getSiblingDB() 选项。
文档 here 其中说:
<块引用>用于在不修改shell环境中的db变量的情况下返回另一个数据库。
因此,这不是 $lookup
而是一种获得另一个数据库数据的方法。