【问题标题】:How to populate one to many relationship in mongoose with parent refrencing?如何使用父引用填充猫鼬中的一对多关系?
【发布时间】:2021-04-11 23:04:21
【问题描述】:

我有三个集合: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'}],
 },
]

我在聚合中的尝试正常工作:

db.parent.aggregate([
  {
    "$lookup": {
      "from": "child1",
      "localField": "_id",
      "foreignField": "parent",
      "as": "child1"
    }
  },
  {
    "$lookup": {
      "from": "child2",
      "localField": "_id",
      "foreignField": "parent",
      "as": "child2"
    }
  }
])

Mongo Playground

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

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

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

【问题讨论】:

  • 到目前为止您尝试过什么?尝试使用 $lookup 进行聚合,您可以在单个查询中使用多个查找。
  • 我在单独数据库中的集合,例如:一个数据库中的父集合和另一个数据库中的 child1 和 child2 coll。只有我可以使用 poplulate
  • 请在您的问题中更新此详细信息,而不是在评论中,我认为不可能在单个查询中查看此打开的Jira ticket-34935 和类似的question1question2跨度>

标签: mongodb mongoose foreign-keys one-to-many mongoose-populate


【解决方案1】:

正如mongoDB docs 所说的$lookup

同一数据库中的未分片集合执行左外连接,以过滤来自“已连接”集合的文档以进行处理。

所以不,不可能跨数据库进行。

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

Docs here 在哪里说:

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

所以,这不是$lookup,而是一种拥有另一个数据库数据的方法。

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 2017-10-11
    • 2020-11-08
    • 2018-01-22
    • 2018-08-23
    • 2015-07-28
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多