distinct() (Distinct Values)
Last updated: 2026-10-09
distinct() (Distinct Values)
distinct() returns every unique value of a given field in the collection, e.g. `db.users.distinct('address.city')`. It returns a deduplicated array of values, not full documents — handy for enumerating categories or available values. Note that distinct on large unindexed fields can be slow, and results are bounded by the 16MB BSON limit.
| Category | Read |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.distinct(<field>, <filter>)
⚙️ Parameters
| field | Field name to deduplicate; dotted paths like 'address.city' work. |
|---|---|
| filter | Optional. Filters documents before collecting values. |
Returns:Array of distinct values; empty when nothing matches.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// distinct: list all cities of adult users
const cities = db.users.distinct(
'address.city',
{ age: { $gt: 18 } }
)
cities
Output:
[ 'Beijing', 'Shanghai', 'Guangzhou' ]
📌 Notes
- Returns an array of values, not counts; use .length to count
- Nested fields use dotted paths such as 'address.city'
- Results are capped at 16MB; use an aggregation pipeline for huge datasets
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow does distinct differ from $group dedup in aggregation?
Adistinct() returns a plain array of unique values; $group can also count, sum, and aggregate in richer ways.
QCan distinct work on nested fields?
AYes — use a dotted path, e.g. db.users.distinct('address.city').
QDoes distinct fail when results are huge?
AIf the result exceeds the 16MB BSON limit it errors; switch to a $group pipeline for very large results.