如何按MongoDB中的计数进行分组?

时间:2017-02-03 08:43:35

标签: mongodb aggregation-framework

我在MongoDB中有一个设备集合。此设备集合有一个现场商店,显示哪个设备属于哪个商店。

我可以通过以下方式获得在商店中使用的设备数量:

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 } }
  ]
)

谢谢Alex

0 个答案:

没有答案