Mongodb Aggregation通过groupby获取记录数

时间:2019-11-11 06:34:20

标签: mongodb

我下面有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",
      averageSignal: { $avg: "$signalStrength" },
      strongestSignal: { $max: "$signalStrength" },
      weakestSignal: { $min: "$signalStrength" },
      averageBars: { $avg: "$signalbars" },
      totalTests: { $sum: 1 },
    }
  },
  { $sort: { carrierName: -1 } },
]

卡住了如何在上述查询中找到测试人员总数

任何帮助都会很棒

0 个答案:

没有答案