Grouping by multiple fields in MongoDB

This is my document structure:

{
    "ip_address" : "192.168.133.12",
    "timestamp" : "2014-08-28T06:41:24",
    "response" : 400,
    "uri" : {
        "term" : "Something",
        "page" : "10",
        "category" : "category 10"
    }
}

      

If I want to do groupby on one "response" field, I will do it like this:

db.collName.aggregate({ $group : {_id : "$response", total : { $sum : 1 }} });

      

How do I group by 2 or say 3 fields? Can multiple fields be grouped together so that they form a collection with similar values?

I mean something like this:

{
    "result" : [ 
        {
            "_id" : "responseValue" + "ip_addressValue",
            "totaling" : 3
        }
    ],
    "ok" : 1
} 

      

+3


source to share


1 answer


Yes, maybe you could do something like below



db.collName.aggregate({ $group : 
 {
   "_id" : {"response":"$response", "ip_address":"$ip_address"}, 
   total : { $sum : 1 }
 } 
});

      

+2


source







All Articles