【问题标题】:How do I match a field of a collection with a field inside array of another collection如何将集合的字段与另一个集合的数组内的字段匹配
【发布时间】:2020-10-01 04:21:35
【问题描述】:

我在 MongoDb 中有 2 个集合并说:

收藏1

[ {"Name" : "foo1", "Place" : "bar1", "Rank" : 1},
  {"Name" : "foo2", "Place" : "bar2", "Rank" : 2},
  {"Name" : "foo3", "Place" : "bar3", "Rank" : 3} ]

收藏2

[ {"DocNo" : "One",
   "DocArray" : [{"Name" : "ABC", "Number" : 1},
                 {"Name" : "DEF", "Number" : 2},
                 {"Name" : "XYZ", "Number" : 4}]},
  {"DocNo" : "Two",
   "DocArray" : [{"Name" : "JKL", "Number" : 5},
                 {"Name" : "GHI", "Number" : 1},
                 {"Name" : "UVW", "Number" : 3}]}
]

我需要在 Collection1 中编写一个查询,其中我有 DocNO 以从 Collection2 获取搜索并仅返回来自 Collection1 的那些文档strong> 其中Rank 字段匹配该特定文档的DocArray 内所有元素的所有Number 字段。

在这个例子中,如果我有DocNo = "Two",那么返回的数组将是这样的:

[ {"Name" : "foo1", "Place" : "bar1", "Rank" : 1},
  {"Name" : "foo3", "Place" : "bar3", "Rank" : 3}]

我需要在一个 mongo 查询中完成所有这些操作

【问题讨论】:

  • 如果你有一个特定的DocNO,你为什么要从Collection 1而不是Collection 2开始?

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您的要求:

我需要在 Collection1 中写一个查询

但我会说你需要在Collection 2 上启动此聚合并在Collection 1 上使用$lookup 阶段

查询:

db.Collection2.aggregate([
  { $match: { DocNo: "Two" } }, // Filter for matching doc
  {
    $lookup: {
      from: "Collection1",
      localField: "DocArray.Number",
      foreignField: "Rank",
      as: "Collection1_docs"
    }
  }
])

测试: mongoplayground

【讨论】:

  • 对不起,我需要在 Collection1 本身上聚合它。谢谢
  • 也可以使用DocArray.Number,因为它是一个数组,所以我认为它需要像DocArray[1].Number 这样的索引,但我需要为 DocArray 中的所有元素过滤它 - 如果我有这个问题是在 Collection2 上听取您的建议和查询
  • @prince47 :如果您在操场链接中清楚地观察我们正在使用数组,则可以完成!有什么理由从Collection 1开始我觉得如果我们从Collection 2开始时事情很容易完成,那么从Collection 1开始是没有意义的
  • 是的。以Collection1 开头是有特定原因的,因此是我的问题。
  • @prince47 : 你还在寻找这个或得到答案吗?
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 2016-07-20
  • 2014-09-16
  • 2017-03-14
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多