如何在MongoDB中按计数分组?
我在MongoDB有一个设备集合。此设备集合有一个现场商店,显示哪个设备属于哪个商店 我可以通过以下方式获得商店中使用的设备数量:如何在MongoDB中按计数分组?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我在MongoDB有一个设备集合。此设备集合有一个现场商店,显示哪个设备属于哪个商店 我可以通过以下方式获得商店中使用的设备数量: db.getCollection('devices').aggregate( [ { $group : { _id : "$shop", count: { $sum: 1 } } } ] ) 但我需要一些不同的数据。我想按设备数量对商店进行分组。结果应
db.getCollection('devices').aggregate(
[
{
$group : {
_id : "$shop",
count: { $sum: 1 }
}
}
]
)
但我需要一些不同的数据。我想按设备数量对商店进行分组。结果应该是:
{
"numberOfDevices": 0,
"numberOfShops": 10
},
{
"numberOfDevices": 1,
"numberOfShops": 15
},
{
"numberOfDevices": 2,
"numberOfShops": 34
}...
等等。对于这样的查询,我应该怎么做
更新:
在Alex Blex发表评论后,我找到了一个解决方案:
db.getCollection('devices').aggregate(
[
{
$group : {
_id : "$shop",
count: { $sum: 1 }
}
},
{
$group: {
_id: "$count" ,
shops: { $addToSet: { shop: "$_id"} }
}
},
{ $sort : { "_id" : 1 } }
]
)
谢谢你,亚历克斯另一个
$group
正在筹备中?也许吧,但我真的不知道如何让你试试?有几个例子。