Sanka Sanjeeva
Sanka Sanjeeva

Reputation: 3520

get sum of values from mongodb database

this is my document in the sensor collection

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

i need to get sum of all value attributes with respect to same Ts date value

output like this

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

give me any suggestions

Upvotes: 0

Views: 71

Answers (1)

hbamithkumara
hbamithkumara

Reputation: 2534

Try this..

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"
    }
  }
]

Reference

Mongodb $sum

Mongodb $group

Mongodb $project

Upvotes: 1

Related Questions