0

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

2
  • Is that needs to be grouped by sensorType, BuildingId & ts also? Seems like same sensor & building has different objects + value even on same day as they're separated by time !! Commented Dec 2, 2019 at 17:31
  • @srinivasy, day should be change and i corrected it. there are different sensors in one building and there are many buildings. i need to get sum of the value of one sensor type in one building for each day. Commented Dec 3, 2019 at 3:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you very much for your reply, the calculation worked perfectly. Can you please tell me how to insert the sum of values for each date(Ts) inside the array CalcItems.Because when we project, two documents are made instead of inserting to the same array. Could you please help.
Can you post the result and sample data here
here sample data and result docs.google.com/document/d/…
Try this Updated demo
that answer worked brilliantly thank you so much it really helped me a lot Thank You
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.