Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get distinct values from a column in MongoDB?
To get distinct values from a column in MongoDB, use the distinct() method. This eliminates duplicate values and returns only unique values from the specified field.
Syntax
db.collection.distinct("fieldName")
Sample Data
Let us create a collection with documents that contain duplicate names ?
db.demo128.insertMany([
{"Name": "Chris"},
{"Name": "David"},
{"Name": "David"},
{"Name": "Bob"},
{"Name": "Chris"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e30583d68e7f832db1a7f5d"),
ObjectId("5e30584068e7f832db1a7f5e"),
ObjectId("5e30584368e7f832db1a7f5f"),
ObjectId("5e30584668e7f832db1a7f60"),
ObjectId("5e30584c68e7f832db1a7f61")
]
}
Display all documents from the collection ?
db.demo128.find();
{ "_id": ObjectId("5e30583d68e7f832db1a7f5d"), "Name": "Chris" }
{ "_id": ObjectId("5e30584068e7f832db1a7f5e"), "Name": "David" }
{ "_id": ObjectId("5e30584368e7f832db1a7f5f"), "Name": "David" }
{ "_id": ObjectId("5e30584668e7f832db1a7f60"), "Name": "Bob" }
{ "_id": ObjectId("5e30584c68e7f832db1a7f61"), "Name": "Chris" }
Example: Get Distinct Values
Get distinct values from the Name field ?
db.demo128.distinct("Name");
[ "Bob", "Chris", "David" ]
Key Points
- The
distinct()method returns an array of unique values - Duplicate values are automatically removed from the result
- Results are sorted alphabetically by default
Conclusion
Use db.collection.distinct("fieldName") to retrieve unique values from any field in MongoDB. This method efficiently eliminates duplicates and returns a clean array of distinct values.
Advertisements
