我在MongoDB中有一个如下所示的数据集:
{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Tom's", "category": "coffee shop" },
{ "name": "Starbucks", "category": "coffee shop" },
{ "name": "Central Park", "category": "park" },
{ "name": "Office", "category": "office" },
{ "name": "Red Lobster", "category": "restaurant" },
{ "name": "Home", "category": "home" },
{ ... } // and so on
如何找到特定类别的最常见值?例如,coffee shop
和restaurant
最常见的值应分别为Tom's和Red Lobster
我当前的$aggregate
查询似乎只列出了所有数据集中最常见的值:
db.collection.aggregate(
{ "$group": { "_id": { "name": "$name" }, "count": { "$sum":1 } }},
{ "$group": { "_id": "$_id.name", "count": { "$sum": "$count" } }},
{ "$sort": { "count":-1 }}
)
答案 0 :(得分:0)
您可以尝试以下查询。
$group
关于类别和名称,以获取每个类别和名称组合的计数。
$sort
输入文件按类别和计数desc。
$group
在$first
类别中选择最常出现的文档。
db.collection_name.aggregate([
{
"$group": {
"_id": {
"category": "$category",
"name": "$name"
},
"count": {
"$sum": 1
}
}
},
{
"$sort": {
"_id.category": 1,
"count": -1
}
},
{
"$group": {
"_id": {
"category": "$_id.category"
},
"name": {
"$first": "$_id.name"
},
"count": {
"$first": "$count"
}
}
}
])