🍃 MongoDB Tutorial

MongoDB distinct() Method: Get Unique Field Values

Learn how to use MongoDB's distinct() method to get every unique value for a field across a collection, filter it, and count the results with .length.

The distinct() Method

distinct() returns every unique value stored in a given field across a collection, as a plain array.

Syntax

db.collection.distinct(field)

Examples

db.employees.distinct("age")
// [ 22, 23, 24, 25, 26 ]

db.employees.distinct("gender")
// [ 'F', 'M' ]

db.employees.distinct("city")
// [ 'Mumbai', 'Palghar', 'Pune' ]

db.employees.distinct("reportinmgr.mgrid")
// works on embedded fields too

Filtering distinct()

Pass a query object as the second argument to get distinct values only from documents that match the filter.

db.employees.distinct("age", { gender: "M" })
// [ 22, 24, 26 ]  -- only ages belonging to male employees

Counting Distinct Values with .length

Chain .length onto the result to get how many unique values there are, without printing the whole array.

db.employees.distinct("age").length
// 5

db.employees.distinct("city").length
// 3

db.employees.distinct("age", { gender: "M" }).length
// 3

Common Errors & Troubleshooting

  • distinct() returning fewer values than expected — check for inconsistent data types across documents (e.g. some documents storing age as a string, others as a number) — MongoDB treats these as genuinely distinct values, not the same one.
  • Large distinct() results causing a memory error on old MongoDB versions — distinct() returns its full result in a single BSON document, which has a size limit; for a field with an enormous number of unique values, use an aggregation $group instead (covered in the Aggregation section).
  • Forgetting the filter argument only scopes which documents are considered, not the values themselves — distinct("age", {gender:"M"}) still returns distinct age values, just only from documents where gender is "M" — it doesn't filter the returned ages by anything else.

Key Takeaways

  • distinct() returns a plain JavaScript array of unique values, not documents.
  • Pass a filter as the second argument to scope the distinct values to a subset of documents.
  • .length on the result is the simplest way to count how many distinct values exist.