Andrii Furmanets
Andrii Furmanets

Reputation: 1161

Mongodb aggregation Count fields which are grouped

I've got the following query::

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

which give the following results:

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

    }, 
    {
        "_id" : "city2"

    }, 
    {
        "_id" : "city3"

    }, 
    {
        "_id" : "city4"

    }
],
"ok" : 1

There are four grouped cities, how can I calculate number of fields which are grouped? Like this:

"result" : [ 
    {
        "count_grouped_fields" : 4

    }, 

Upvotes: 0

Views: 65

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

You can add another $group pipeline:

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

Or use the distinct command (no aggregation) :

db.collection.distinct("city")

Upvotes: 1

Related Questions