计算跨MongoDB集合的数组中出现的唯一值的次数

时间:2016-08-03 14:23:50

标签: mongodb mongoose mongodb-query

所以我有一组用户。用户文档是一个非常简单的文档,如下所示:

{
   username: "player101",
   badges: ["score10", "score100"]
}

那么我如何查询以查看徽章数组中每个唯一值在整个集合中出现的次数?

1 个答案:

答案 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 }