与组的MongoDB聚合查询太慢

时间:2019-11-21 13:28:17

标签: mongodb aggregation-framework

我下面有Signal记录集合:

Signal records:

[
  {
    "id": "5dc250e0d972e71c3b3e6e88",
    "signalStrength": -180,
    "signalbars": "3",
    "employee": "5db59227f0204855654075ee",
    "store": "5dc25092d972e71c3b3e6e87",
    "carrierName": "LT&T"
  },
  {
    "id": "5dc251f723760a24de167f8e",
    "signalStrength": -180,
    "signalbars": "3",
    "employee": "5db59227f0204855654075ee",
    "store": "5dc25092d972e71c3b3e6e87",
    "carrierName": "Sprint"
  },
  {
    "id": "5dc289affd1ea02f0fceb9ac",
    "signalStrength": -80,
    "signalbars": "3",
    "employee": "5db59227f0204855654075ee",
    "store": "5dc2899bfd1ea02f0fceb9ab",
    "carrierName": "LT&T"
  }
]

基本上,我需要根据运营商名称的平均值和拥有该运营商名称的信号记录的员工总数来计算

我需要得到以下结果

[
      {
        "_id": "LT&T",
        "averageSignal": -130,
        "strongestSignal": -80,
        "weakestSignal": -180,
        "averageBars": 3,
        "totalTests": 2,
        "totalTesters": 1
      },
      {
        "_id": "Sprint",
        "averageSignal": -180,
        "strongestSignal": -180,
        "weakestSignal": -180,
        "averageBars": 3,
        "totalTests": 1,
        "totalTesters": 1
      }
]

我的代码在下面进行汇总:

[
  {
    $match: query
  },
  {
    $group:
    {
      _id: "$carrierName",
      employee: { "$addToSet": "$employee" },
      averageSignal: { $avg: "$signalStrength" },
      strongestSignal: { $max: "$signalStrength" },
      weakestSignal: { $min: "$signalStrength" },
      averageBars: { $avg: "$signalbars" },
      totalTests: { $sum: 1 },
      totalTesters: { $sum: 1 },
    }
  },
  { $addFields: { totalTesters: { $size: "$employee" } } },
  { $sort: { averageSignal: -1 } },
];

它按我的预期工作。但是,尽管记录在5万以内,但要花很长时间才能得到结果。

有人可以帮助我提高性能吗?

0 个答案:

没有答案