MongoDB aggregate/grouping by key-value pairs

Viewed 2773

My data looks something like this:

    { 
            "_id" : "9aa072e4-b706-47e6-9607-1a39e904a05a", 
            "customerId" : "2164289-4", 
            "channelStatuses" : {
                    "FOO" : {
                    "status" : "done"
                    }, 
                    "BAR" : {
                    "status" : "error"
                    }
            }, 
            "channel" : "BAR", 
    }

My aggregate/group looks like this:

    { 
            "_id" : {
                    "customerId" : "$customerId", 
                    "channel" : "$channel", 
                    "status" : "$channelStatuses[$channel].status"
            }, 
                    "count" : {
                    "$sum" : 1
            }
    }

So basically with the example data the group should give me a group grouped by:

   {"customerId": "2164289-4", "channel": "BAR", "status": "error"}

But I cannot use []-indexing in a aggregate/group. What should I do instead?

1 Answers
Related