Skip to main content
100%

MongoDB Aggregation Framework way for "select count (distinct fieldName) from someTable" for large collections

✓ Published0🌍 Public
Aackuser
Last edited Aug 2, 2012
Created on May 23, 2016

This example shows how to compute the equivalent of a SQL “select count (distinct fieldName) from someTable” using MongoDB’s Aggregation Framework for large collections. The code uses the `db.someCollection.aggregate()` method with two `$group` stages: the first groups documents by the distinct value of `fieldName` (assigned to `_id`), and the second groups all results into a single document (`_id: 1`) while summing the number of groups with `$sum: 1` to produce the final count. The snippet is written as a JavaScript gist and relies solely on MongoDB’s native aggregation pipeline, with no external visualization library.

AI-generated description

Similar vizzes