Results, Sorting & Pagination
distinct()
Unique values for a field, with an optional filter, returned as a simple array.
distinct returns the unique values of one field, as a JavaScript array — not documents. Optional second argument: a filter. It is a dropdown of cities, not a report. Totals per city are $group (Aggregation).
db.users.distinct("city")
db.users.distinct("city", { isActive: true })[ "Bangalore", "Pune", "Mumbai" ]
On an array field, distinct walks the elements: distinct("skills") can return "Node.js" and "MongoDB" as separate values, not the whole array. Null and missing fields are skipped. Large distincts still scan; this is not a substitute for a values collection you maintain on write.
Interview question
What does distinct() return, and when is $group the better tool?
An array of unique values for one field, optionally filtered. $group when I need a count, a sum, or several fields per bucket. distinct is a list; $group is a report.