所以我有一组用户。用户文档是一个非常简单的文档,如下所示:
{
username: "player101",
badges: ["score10", "score100"]
}
那么我如何查询以查看徽章数组中每个唯一值在整个集合中出现的次数?
答案 0 :(得分:1)
在aggregation和$unwind
阶段使用$group
,您可以使用$sum
算术运算符对徽章求和
db.players.aggregate([
{
$unwind: "$badges"
},
{
$group:
{
_id: "$badges",
count: { $sum: 1 }
}
}
]);
带有文档的集合players
上的
{ "username" : "player101", "badges" : [ "score10", "score100" ] }
{ "username" : "player102", "badges" : [ "score11", "score100" ] }
{ "username" : "player103", "badges" : [ "score11", "score101" ] }
{ "username" : "player104", "badges" : [ "score12", "score100" ] }
为您提供结果
{ "_id" : "score101", "count" : 1 }
{ "_id" : "score11", "count" : 2 }
{ "_id" : "score12", "count" : 1 }
{ "_id" : "score100", "count" : 3 }
{ "_id" : "score10", "count" : 1 }