MongoDB:将具有相同公共值的不同字段分组

时间:2020-07-26 10:27:55

标签: mongodb mongoose mongodb-query aggregation-framework aggregation

我需要对mongodb集合执行汇总。但是我找不到正确的聚合管道。

实际上,当doc1.fieldTarget == doc2.fieldSource && doc2.fieldTarget == doc3.fieldSource

时,我需要获取不同文档的ID。

例如,我要在目标(docA)与(docB的来源)相同时查找所有文档,然后验证其目标是否为其他任何文件的来源

这是有关通过端口号查找目标服务器的信息。

示例文档:

 [{
    _id: 11,
    portSource: 1,
    portTarget: 2,
    status:active
  },
  {
    _id: 22,
    portSource: 2,
    portTarget: 3
    status:passive
  },
  {
    _id: 33,
    portSource: 3,
    portTarget: 10
    status:active
  },
   {
    _id: 44,
    portSource: 3,
    portTarget: 5
    status:passive
  },
 {
    _id: 55,
    portSource: 5,
    portTarget: 7
    status:active
  },
 {
    _id: 66,
    portSource: 12,
    portTarget: 4
    status:active
  },
 {
    _id: 77,
    portSource: 4,
    portTarget: 16
    status:passive
  },
 {
    _id: 88,
    portSource: 4,
    portTarget: 246
    status:active
  },
 {
    _id: 99,
    portSource: 246,
    portTarget: 500
    status:active
  },
]

我想要的支出:

[
 {
  portSource: 1, portTarget: 10, sourceId : 11, targetId: 33
 },
 {
  portSource: 1, portTarget: 7, sourceId : 11, targetId: 55
 }
]

该段添加假设(AB + BC = AC)。

如果有“ B”,请告诉我我们在“ A”和“ C”之间有联系

注1:该路径通常看起来像AB + BC + CD或更多,并且期望的结果是A-> D,如带有id:11 && id:55的示例所示

注释2:未返回id:66,因为id:77的端口16与潜在的“ C”不匹配

注释3:因为id:66不是被动的“ B”,所以未返回id:88

谢谢!

0 个答案:

没有答案