The $group in mongo mostly seems to be used to group by values that are same. For these mongo documents:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") }
{ "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") }
{ "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") }
{ $group : { _id : "$price" } }
will get me three documents with prices 5, 10, 20. But what if want to extend the definition of group to something more than "equals". What if I have a dictionary of the following structure:
{
"tens" : [10,20,30,40],
"fives" : [5,15,25,35]
}
and want to group all documents with prices in "tens" array together and "fives" array into another document. Something like:
{ "_id" : "fives", "quantity" : 30 }
{ "_id" : "tens" , "quantity" : 13 }
Any way to achieve that using the aggregation pipeline without having to resort to Map-Reduce?
_idfield, it will be a transformation outputting your distinct group key. So here why don't you use just{_id: {$mod: ["$price", 10]}, quantity: {$sum: "$quantity"}}? The aggregation should result:{ "_id" : 5, "quantity" : 30 }, { "_id" : 0 , "quantity" : 13 }. I do not post it as an answer because I cannot test it right now. - dgiugg