In MongoDB, distinct() is used to find unique values of a particular field from a collection. It returns the unique values in an array.
Syntax
db.collection.distinct("fieldName")
Example: Employee Collection
Suppose emp contains:
{ empno: 1, ename: "Amit", dept: "IT", salary: 25000 }
{ empno: 2, ename: "Ravi", dept: "HR", salary: 30000 }
{ empno: 3, ename: "Neha", dept: "IT", salary: 28000 }
{ empno: 4, ename: "Raj", dept: "Sales", salary: 35000 }
{ empno: 5, ename: "Priya", dept: "HR", salary: 32000 }
1. Find distinct departments
db.emp.distinct("dept")
Output:
[ "IT", "HR", "Sales" ]
Even though IT and HR occur multiple times, they are returned only once.
2. Find distinct employee names
db.emp.distinct("ename")
Output:
[ "Amit", "Ravi", "Neha", "Raj", "Priya" ]
3. Distinct with a condition
You can provide a query as the second argument. MongoDB’s syntax is:
db.collection.distinct("field", { condition })
For example, find distinct departments where salary is greater than 28000:
db.emp.distinct("dept", { salary: { $gt: 28000 } })
Output:
[ "HR", "Sales" ]
4. Distinct values of salary
db.emp.distinct("salary")
Output:
[ 25000, 30000, 28000, 35000, 32000 ]
5. Distinct values from an array
If documents contain:
{ name: "A", skills: ["Java", "MongoDB"] }
{ name: "B", skills: ["Python", "MongoDB"] }
{ name: "C", skills: ["Java", "PHP"] }
Then:
db.student.distinct("skills")
returns:
[ "Java", "MongoDB", "Python", "PHP" ]
MongoDB treats array elements as individual values for distinct().
⭐ Important Difference
| Command | Purpose |
|---|---|
find() | Returns documents |
distinct() | Returns unique values |