【问题标题】:Mongodb aggregation Count fields which are groupedMongodb聚合计数分组的字段
【发布时间】:2014-02-27 00:01:29
【问题描述】:

我有以下查询::

db.collection.aggregate({'$group':{
  '_id': "$city"
}})

给出以下结果:

"result" : [ 
    {
        "_id" : "city1"

    }, 
    {
        "_id" : "city2"

    }, 
    {
        "_id" : "city3"

    }, 
    {
        "_id" : "city4"

    }
],
"ok" : 1

有四个分组的城市,如何计算分组的字段数? 像这样:

"result" : [ 
    {
        "count_grouped_fields" : 4

    }, 

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以添加另一个$group 管道:

    {$group:{'_id': "city_count", count : { $sum : 1 }}}

    或者使用 distinct 命令(不聚合):

    db.collection.distinct("city")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多