如何使用父引用填充猫鼬中的一对多关系?

问题描述

我有三个集合:parent、child1、child2。

父集合:

[{_id:1},{_id:2},{_id:3}]

child1 集合:

[{_id:1,child1:'a',parent:1},{_id:2,child1:'b',{_id:3,child1:'c',parent:2}]

child2 集合:

[{_id:1,child1:'d',parent:2},child1:'e',parent:3}]

集合 child1 和 child2 引用父集合。

现在,我想在 mongoose 中进行查询以获得如下结果:

[
 {
  _id:1,child1:[{_id:1,child1:'a'},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","as": "child2"
    }
  }
])

Mongo Playground

当集合在同一个数据库中但我的集合在单独的数据库中时,这有效。

例如:父数据库中的父集合和子数据库中的 child1 和 child2 集合。

您对跨多个数据库使用聚合有什么想法,或者我如何使用 populate 来解决这个问题?

解决方法

正如 mongoDB docs 所说的关于 $lookup

相同数据库中的未分片集合执行左外部联接,以从“联接”集合中过滤文档以进行处理。

所以不,不可能跨数据库这样做。

但是,作为补充,使用 Mongo 存在 db.getSiblingDB() 选项。

文档 here 其中说:

用于在不修改shell环境中的db变量的情况下返回另一个数据库。

因此,这不是 $lookup 而是一种获得另一个数据库数据的方法。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...