mongodb 如何在两个具有可变大小对象属性的集合上使用查找

bfrts1fy  于 2023-01-01  发布在  Go
关注(0)|答案(1)|浏览(164)

我有两个集合,一个是company,另一个是reports,所以下面是我的公司集合。

    • 公司集合**
[
 {
  company_id:1,
  hubId:4
  dimensions:{ region:'North america',country:'USA'},
  name:'Amsol Inc.'
 },
 {
   company_id:1,
   hubId:4
   dimensions:{ region:'North america',country:'Canada'},
   name:'Amsol Inc.'
 },
 {
   company_id:2,
   hubId:7
   dimensions:{ region:'North america',country:'USA',revenue:34555},
   name:'Microsoft Inc.'
 }
]
    • 报告收集**
[
 {
  report_id:1,
  name:'example report',
  hubId:4
  dimensions:{ region:'North america',country:'USA'},
  name:'Amsol Inc.'
 },
 {
   report_id:2,
   name:'example report',
   hubId:4
   dimensions:{ region:'North america',country:'Canada'},
   name:'Amsol Inc.'
 },
 {
   report_id:3,
   name:'example report',
   hubId:5
   dimensions:{ region:'North america',country:'USA',revenue:20000},
   name:'Microsoft Inc.'
 }
 {
   report_id:4,
   name:'example report',
   hubId:4
   dimensions:{region:'North america',country:'Greenland'},
   name:'Amsol Inc.'
 },
]
    • 输出**
[
  {
  report_id:1,
  name:'example report',
  hubId:4
  dimensions:{ region:'North america',country:'USA'},
  name:'Amsol Inc.'
 },
 {
   report_id:2,
   name:'example report',
   hubId:4,
   dimensions:{region:'North america',country:'Canada'},
   name:'Amsol Inc.'
 }
]

我想获取所有具有相同HubIddimensions的公司的报告。
例如:hubId = 4company集合中有2家公司,但它们具有不同的维度,因此在这里我想搜索具有hubId = 4和维度的所有报告,如与这些公司中的任何一家匹配。
收藏品里有成千上万张这样的唱片。
我一直在寻找一些聚合管道,但不明白我如何才能应用这里的逻辑得到这里的结果。
有人帮我得到想要的结果。任何帮助感激。

nbysray5

nbysray51#

如果我没有理解错的话,一个带管道的$lookup就可以完成这项工作:let定义reports集合中的参数,这些参数与$lookup管道内的$$一起使用。$参数用于$lookup管道的上下文,即company集合。
$setEquals用于测试数组的相等性,其中项的顺序并不重要。这里它与$objectToArray一起用于测试对象的相等性(对象将被更改为数组,然后进行比较)。

db.reports.aggregate([
  {$lookup: {
      from: "company",
      let: {hubId: "$hubId", dimensions: "$dimensions"},      
      as: "companies",
      pipeline: [
        {$match: {
            $expr: {
              $and: [
                {$eq: ["$hubId", "$$hubId"]},
                {$setEquals: [
                    {$objectToArray: "$dimensions"},
                    {$objectToArray: "$$dimensions"}
                ]}
              ]
            }
        }},
        {$project: {_id: 1}}
      ]
  }},
  {$match: {"companies.0": {$exists: true}}},
  {$unset: "companies"}
])

了解它在playground example上的工作原理

相关问题