从mongodb数据库获取值的总和

时间:2019-12-02 11:11:12

标签: mongodb

这是我传感器集合中的文档

sensorId:1
sensorType:1
BuildingId:1
CalcItems:
    0: Object
        Ts:2019-08-30T18:30:00.000+00:00
        Value:1
    1:Object
        Ts:2019-08-31T19:00:00.000+00:00
        Value:2

我需要获得关于同一Ts日期值的所有值属性的总和

这样的输出

sensorType:1
BuildingId:1
CalcItems:
    0: Object
        Ts:2019-08-31T18:30:00.000+00:00
        Value:23
    1:Object
        Ts:2019-08-31T19:00:00.000+00:00
        Value:43

给我任何建议

1 个答案:

答案 0 :(得分:0)

尝试一下。

Sample live demo

[
  {
    "$unwind": "$CalcItems"
  },
  {
    $group: {
      _id: {
        "sensorType": "$sensorType",
        "BuildingId": "$BuildingId",
        "Ts": "$CalcItems.Ts"
      },
      "total": {
        "$sum": "$CalcItems.Value"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "sensorType": "$_id.sensorType",
      "BuildingIdVal": "$_id.BuildingId",
      "CalcItems.Ts": "$_id.Ts",
      "CalcItems.Value": "$total"
    }
  }
]

参考

Mongodb $sum

Mongodb $group

Mongodb $project