Let's say we have a collection as follows
{ "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] },
{ "_id" : 2, "item" : "EFG", "sizes": [ "S" ] },
{ "_id" : 3, "item" : "ABC", "sizes": [ "M" ] }
How can we list the items in the array (sizes) and the quantity of items associated to the sizes
For example
size 'S', item 'ABC' = 1
size 'S', item 'EFG' = 1
size 'M', item 'ABC' = 2
size 'L', item 'ABC' = 1
Note that size 'M' has to instances where item is 'ABC'.
I tried the following
db.collection.group(
{
key: {'sizes': true},
initial: {sum: 0},
reduce: function(doc, prev) { prev.sum += 1}
});
but it doesn't unwind the array and I can not seem to able to add the Item as part of the group count
Any ideas?
Thanks