0
0
MongodbHow-ToBeginner · 3 min read

How to Use Distinct in MongoDB: Syntax and Examples

In MongoDB, use the distinct method to find unique values for a specified field in a collection. It returns an array of distinct values matching an optional query filter.
📐

Syntax

The distinct method has this basic syntax:

  • db.collection.distinct(field, query)

Here, field is the name of the field you want unique values from, and query is an optional filter to limit which documents are checked.

mongodb
db.collection.distinct(field, query)
💻

Example

This example shows how to get all unique values of the category field from the products collection, filtering only products with price greater than 20.

mongodb
db.products.distinct("category", { price: { $gt: 20 } })
Output
["electronics", "furniture", "clothing"]
⚠️

Common Pitfalls

Common mistakes when using distinct include:

  • Not providing the field name as a string, which causes errors.
  • Expecting distinct to return documents instead of just unique values.
  • Using distinct without a query filter and getting unexpected results if the collection is large.
mongodb
/* Wrong: field name not a string */
db.products.distinct("category")

/* Right: field name as string */
db.products.distinct("category")
📊

Quick Reference

Use distinct to get unique values of a field. You can add a query filter to narrow results. It returns an array of values, not documents.

ParameterDescription
fieldThe field name to find distinct values for (string)
queryOptional filter to select documents (object)
ReturnArray of unique values for the field

Key Takeaways

Use db.collection.distinct(field, query) to get unique values of a field.
Always provide the field name as a string in distinct.
You can add a query filter to limit which documents are checked.
Distinct returns an array of values, not full documents.
Avoid using distinct on very large collections without filters for performance.