Skip to content

Results, Sorting & Pagination

distinct()

Unique values for a field, with an optional filter, returned as a simple array.

BeginnerAbout 3 minutes

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 })
Every city we have users in. Then only active users.
[ "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?

Think about it first.