如何计算MongoDB中所有元素的出现次数?

时间:2014-11-27 19:45:49

标签: mongodb

我们说我的MongoDB中有以下条目。

{ "_id" : ObjectId("5474af69d4b28042fb63b81b"), "name" : "a", "time" : NumberLong("1412774562000"), "location" : "DE" }
{ "_id" : ObjectId("5474af69d4b28042fb63b81c"), "name" : "b", "time" : NumberLong("1412774562020"), "location" : "DE" }
{ "_id" : ObjectId("5474af69d4b28042fb63b81d"), "name" : "c", "time" : NumberLong("1412774562040"), "location" : "US" }
{ "_id" : ObjectId("5474af69d4b28042fb63b81e"), "name" : "d", "time" : NumberLong("1412774562060"), "location" : "AU" }
{ "_id" : ObjectId("5474af69d4b28042fb63b81f"), "name" : "e", "time" : NumberLong("1412774562080"), "location" : "CN" }

因此,我需要知道每个特定"位置"的频率。可以在数据库中找到,例如

{"DE": "2",
 "US": "1",
 "AU": "1",
 "CN": "1"}

我没有关于数据库中所有不同位置的信息,因此在已知位置之后查询,例如

db.c.find({"location": "DE"})

无法解决我的问题。

1 个答案:

答案 0 :(得分:2)

您需要将aggregation管道与groupproject阶段运算符结合使用。

db.c.aggregate([
{$group:{"_id":"$location","count":{$sum:1}}},
{$project:{"location":"$_id","occurance":"$count"}}
])