Reputation: 691
So I have a collection of users. The user document is a very simple document, and looks like this:
{
username: "player101",
badges: ["score10", "score100"]
}
So how can I query to see how many times each unique value in the badges array occurs across the entire collection?
Upvotes: 0
Views: 394
Reputation: 6652
Use aggregation with $unwind
and $group
stages, where you can sum badges with $sum
arithmetic operator
db.players.aggregate([
{
$unwind: "$badges"
},
{
$group:
{
_id: "$badges",
count: { $sum: 1 }
}
}
]);
on collection players
with documents
{ "username" : "player101", "badges" : [ "score10", "score100" ] }
{ "username" : "player102", "badges" : [ "score11", "score100" ] }
{ "username" : "player103", "badges" : [ "score11", "score101" ] }
{ "username" : "player104", "badges" : [ "score12", "score100" ] }
gives you the result
{ "_id" : "score101", "count" : 1 }
{ "_id" : "score11", "count" : 2 }
{ "_id" : "score12", "count" : 1 }
{ "_id" : "score100", "count" : 3 }
{ "_id" : "score10", "count" : 1 }
Upvotes: 1