Skip to main content
100%

MongoDB equivalent of an SQL query to get the distinct values of a field in a collection including the count of documents which have each distinct value (distinct with count)

✓ Published0🌍 Public
Aackuser
Last edited Aug 10, 2015
Created on May 23, 2016

This example demonstrates how to retrieve distinct values of a field in a MongoDB collection along with the document count for each value, mirroring a SQL `GROUP BY` query. It shows two aggregation pipelines using MongoDB’s `aggregate()` method with the `$group` stage to group by the field `_id` and compute a `count` via `$sum:1`, and an optional `$sort` stage to order the results by count descending. The first pipeline returns unsorted counts, while the second sorts them from highest to lowest. No external visualization library is used; the output is raw aggregated data from the database.

AI-generated description

Similar vizzes