Skip to content

Instantly share code, notes, and snippets.

@eranation
Created August 2, 2012 22:51
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save eranation/3241616 to your computer and use it in GitHub Desktop.
Save eranation/3241616 to your computer and use it in GitHub Desktop.
MongoDB Aggregation Framework way for "select count (distinct fieldName) from someTable" for large collections
//equivalent of "select count (distinct fieldName) from someTable"
db.someCollection.aggregate([{ $group: { _id: "$fieldName"} },{ $group: { _id: 1, count: { $sum: 1 } } } ])
@clarkenheim
Copy link

Found this ^ when i wanted this: https://gist.github.com/clarkenheim/fa0f9e5400412b6a0f9d
returns a result with the distinct field names, and a count of the documents in the collection which have each distinct field value.

@wuyuting
Copy link

it works!

@vadymberkut
Copy link

Nice

@smartinov
Copy link

Noice!

@maowerner
Copy link

nice

@FedericoHeichou
Copy link

db.a.aggregate([{"$match": {"port": 80}}, {"$group": { "_id": "$ip"}}, {"$count": "count"}])

This seems cuter (I added a match too)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment