1

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

1 Answer 1

2

You need to $unwind the "sizes" array then $group by "item" and "sizes" and use the $sum to return the count.

db.collection.aggregate(
    [ 
        { "$unwind": "$sizes" }, 
        { "$group": { 
            "_id": { 
                "item": "$item", 
                "sizes": "$sizes" 
            }, 
            "count": { "$sum": 1 } 
        }}
    ]
) 

which produces:

{ "_id" : { "item" : "EFG", "sizes" : "S" }, "count" : 1 }
{ "_id" : { "item" : "ABC", "sizes" : "L" }, "count" : 1 }
{ "_id" : { "item" : "ABC", "sizes" : "M" }, "count" : 2 }
{ "_id" : { "item" : "ABC", "sizes" : "S" }, "count" : 1 }
Sign up to request clarification or add additional context in comments.

1 Comment

This is fantastic, thank you. I was a bit puzzled on how to get the $unwind to work. This is great!!

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.