首页 > 解决方案 > 如何在 mongodb 中获取图形的条件平均数据?

问题描述

资料一:

{
    "_id" : "5eb922b4c019811689c8f8e3",
    "createdAt" : "2020-05-10T19:30:00.000Z",
    "isManual" : false,
    "value" : 0.66
}

数据2:

{
    "_id" : "5eb922b4c019811689c8f8e3",
    "createdAt" : "2020-05-10T19:30:00.000Z",
    "isManual" : false,
    "value" : 0.52
}

数据3:

    {
        "_id" : "5eb922b4c019811689c8f8e3",
        "createdAt" : "2020-05-10T19:30:00.000Z",
        "isManual" : true,
        "value" : 0.34
    }

现在我需要生成一个查询来获取字段的平均值。考虑平均的isManual 键:

Response key expected:
total_fields = 3
manual_avg = 0.34 ((0.66 + 0.52)/3)
not_manual_avg = 0.13 ((0.34)/3)

标签: node.jsmongodbmongoosemongodb-queryaggregate

解决方案


您可以尝试以下聚合查询:

db.collection.aggregate([
    /** group all docs in collection */
    {
      $group: {
        _id: null,
        total_fields: { $sum: 1 }, /** count total no.of docs */
        manual_avg: { $avg: { $cond: [ "$isManual", 0, "$value" ] } }, /** If 'isManual' is true pass-in 0 else actual value to average */
        not_manual_avg: { $avg: { $cond: [ "$isManual", "$value", 0 ] } }
      }
    },
    /** Optional stage */
    {
      $project: { _id: 0,total_fields: 1, manual_avg: { $trunc: [ "$manual_avg", 2 ] }, not_manual_avg: { $trunc: [ "$not_manual_avg", 2 ] }
      }
    }
  ])

测试: mongoplayground


推荐阅读