0
因此,我有一組用戶。用戶文件是一個非常簡單的文件,如下所示:統計整個MongoDB集合中數組中唯一值的出現次數
{
username: "player101",
badges: ["score10", "score100"]
}
所以,我怎麼可以查詢看到徽章陣列中的每個獨特的價值有多少次在整個回收時?
因此,我有一組用戶。用戶文件是一個非常簡單的文件,如下所示:統計整個MongoDB集合中數組中唯一值的出現次數
{
username: "player101",
badges: ["score10", "score100"]
}
所以,我怎麼可以查詢看到徽章陣列中的每個獨特的價值有多少次在整個回收時?
使用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 }