Count values in array of objects

It sorts by and counts across all documents in the collection.

Collection:

db.test01.find()
{ “_id” : ObjectId(“5fd906d828eb4534ccbceb9a”), “name” : “Test”, “votes” : [ { “user” : “joe”, “action” : “up” }, { “user” : “john”, “action” : “up” }, { “user” : “jane”, “action” : “down” } ] }
{ “_id” : ObjectId(“5fd90b3728eb4534ccbceb9b”), “name” : “Test1”, “votes” : [ { “user” : “joe”, “action” : “up” }, { “user” : “john”, “action” : “up” }, { “user” : “jane”, “action” : “down” } ] }

Aggregation result:

db.test01.aggregate([ { $unwind: “$votes” }, { $sortByCount: “$votes.action” } ])
{ “_id” : “up”, “count” : 4 }
{ “_id” : “down”, “count” : 2 }

Just add a $match to get per name:

db.test01.aggregate([ { $match: { name: “Test” } }, { $unwind: “$votes” }, { $sortByCount: “$votes.action” } ])
{ “_id” : “up”, “count” : 2 }
{ “_id” : “down”, “count” : 1 }

All the best,

– Rodrigo

3 Likes