MongoDB Query to Find Unique Values Easily
Use the MongoDB
distinct method to find unique values for a field, like db.collection.distinct('fieldName').Examples
Inputdb.users.distinct('age')
Output[25, 30, 35]
Inputdb.orders.distinct('status')
Output["pending", "shipped", "delivered"]
Inputdb.products.distinct('category')
Output[]
How to Think About It
To find unique values in MongoDB, think about getting all values of a field and then removing duplicates. MongoDB provides the
distinct method that does this for you by scanning the collection and returning only unique entries for the specified field.Algorithm
1
Choose the collection to search.2
Specify the field for which you want unique values.3
Use the <code>distinct</code> method on the collection with the field name.4
Retrieve the list of unique values returned by the query.Code
mongodb
const uniqueAges = db.users.distinct('age'); printjson(uniqueAges);
Output
[25, 30, 35]
Dry Run
Let's trace finding unique ages from a users collection with ages [25, 30, 25, 35, 30].
1
Call distinct on 'age'
db.users.distinct('age')
2
MongoDB scans all documents
Find ages: 25, 30, 25, 35, 30
3
Return unique values
[25, 30, 35]
| Document | Age Found | Unique Values So Far |
|---|---|---|
| 1 | 25 | [25] |
| 2 | 30 | [25, 30] |
| 3 | 25 | [25, 30] |
| 4 | 35 | [25, 30, 35] |
| 5 | 30 | [25, 30, 35] |
Why This Works
Step 1: Use distinct method
The distinct method tells MongoDB to find unique values for a given field.
Step 2: Scan collection
MongoDB looks through all documents in the collection to collect values of the specified field.
Step 3: Remove duplicates
It automatically removes duplicate values and returns only unique ones.
Alternative Approaches
Aggregation with $group
mongodb
db.collection.aggregate([
{ $group: { _id: "$fieldName" } },
{ $project: { _id: 0, uniqueValue: "$_id" } }
])More flexible for complex queries but more verbose and slower than distinct.
Map-Reduce
mongodb
db.collection.mapReduce( function() { emit(this.fieldName, null); }, function(key, values) { return null; }, { out: { inline: 1 } } )
Powerful but more complex and generally slower; use only if aggregation or distinct don't fit.
Complexity: O(n) time, O(k) space
Time Complexity
The distinct method scans all documents (n) to collect values, so it runs in O(n) time.
Space Complexity
It stores unique values (k) in memory, so space is O(k), where k is number of unique values.
Which Approach is Fastest?
distinct is fastest for simple unique value queries; aggregation and map-reduce add overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| distinct | O(n) | O(k) | Simple unique value queries |
| Aggregation with $group | O(n) | O(k) | Complex grouping and filtering |
| Map-Reduce | O(n) | O(k) | Very complex processing, legacy use |
Use
distinct for simple unique value queries as it is fast and easy.Trying to use
find with distinct logic manually instead of using the built-in distinct method.