MongoDB aggregation, find number of distinct values in documents' arrays

Viewed 1342

Reading the docs, I see you can get the number of elements in document arrays. For example given the following documents:

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }

and the following query:

db.inventory.aggregate([{$project: {item: 1, numberOfColors: { $size: "$colors" }}}])

We would get the number of elements in each document's colors array:

{ "_id" : 1, "item" : "ABC1", "numberOfColors" : 3 }
{ "_id" : 2, "item" : "ABC2", "numberOfColors" : 1 }
{ "_id" : 3, "item" : "XYZ1", "numberOfColors" : 0 }

I've not been able to figure out if and how you could sum up all the colors in all the documents directly from a query, ie:

{ "totalColors": 4 }
2 Answers
Related