0

I'm trying to get the sum of "Duration" from mongo subdocument's using aggregate, Here I have event_id = "5656b3655b9e5c8812000007", I need to get the sum of "Duration" field by matching the event_id = "5656b3655b9e5c8812000007" in above example.

Example:

"history" : [
        {
            "timestamp" : "2015-10-26 14:39:15", 
            "event" : "Creation", 
            "createdby" : "Ws", 
            "data" : [
                {
                    "crm_base_contact_id" : "1847", 
                    "crm_imported_files_id" : ""
                }
            ]
        }, 
        {
            "timestamp" : "2015-10-26 15:12:28", 
            "event" : "Task", 
            "createdby" : "Auto-Filter", 
            "data" : [
                {
                    "Campaign ID" : "219", 
                    "Campaign Name" : "ASA", 
                    "Task ID" : "2541639", 
                    "Filter Name" : "ASA", 
                    "Filter ID" : "826"
                }
            ]
        }, 
        {
            "event_id" : ObjectId("5656b3655b9e5c8812000007"), 
            "timestamp" : "2015-11-26 08:23:17", 
            "event" : "Session", 
            "createdby" : "ABC", 
            "data" : [
                {
                    "Campaign ID" : "219", 
                    "Task ID" : "2541639", 
                    "viopCalls" : [
                        {
                            "timestamp" : "2015-11-26 08:25:42", 
                            "CallID" : "46", 
                            "Duration" : NumberInt(5), 
                            "TelNumber" : "0685356189"
                        }, 
                        {
                            "timestamp" : "2015-11-26 08:26:13", 
                            "CallID" : "45", 
                            "Duration" : NumberInt(3), 
                            "TelNumber" : "0685356189"
                        }
                    ]
                }
            ]             
        }
    ], 


Expected output : Duration : 8

Please can anyone help me to get the sum of duration column !!!

2
  • is history a key in collection? Commented Nov 26, 2015 at 9:39
  • yes its a key in collection Commented Nov 26, 2015 at 9:40

1 Answer 1

1

Use can use the following aggregate query:

db.collection.aggregate(
  {$unwind: '$history'},
  {$match: {'history.event_id': ObjectId("5656b3655b9e5c8812000007")}},
  {$unwind: '$history.data'},
  {$unwind: '$history.data.viopCalls'},
  {$group: {_id: null, duration: {$sum: '$history.data.viopCalls.Duration'}}}
)

Result:

{ "_id" : null, "duration" : 8 }
Sign up to request clarification or add additional context in comments.

Comments

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.