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 record values in MongoDB?
The distinct() method in MongoDB returns unique values for a specified field across all documents in a collection, automatically removing duplicates.
Syntax
db.collectionName.distinct("fieldName");
Sample Data
db.distinctRecordDemo.insertMany([
{"StudentId": 1, "StudentName": "John", "StudentAge": 21},
{"StudentId": 2, "StudentName": "John", "StudentAge": 22},
{"StudentId": 3, "StudentName": "Carol", "StudentAge": 21},
{"StudentId": 4, "StudentName": "Carol", "StudentAge": 26},
{"StudentId": 5, "StudentName": "Sam", "StudentAge": 24},
{"StudentId": 6, "StudentName": "Mike", "StudentAge": 27},
{"StudentId": 7, "StudentName": "Sam", "StudentAge": 28}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c77a78299b97a65744c1b50"),
ObjectId("5c77a78b99b97a65744c1b51"),
ObjectId("5c77a79a99b97a65744c1b52"),
ObjectId("5c77a7a499b97a65744c1b53"),
ObjectId("5c77a7b499b97a65744c1b54"),
ObjectId("5c77a7c799b97a65744c1b55"),
ObjectId("5c77a7d399b97a65744c1b56")
]
}
View Sample Data
db.distinctRecordDemo.find().pretty();
{
"_id": ObjectId("5c77a78299b97a65744c1b50"),
"StudentId": 1,
"StudentName": "John",
"StudentAge": 21
}
{
"_id": ObjectId("5c77a78b99b97a65744c1b51"),
"StudentId": 2,
"StudentName": "John",
"StudentAge": 22
}
{
"_id": ObjectId("5c77a79a99b97a65744c1b52"),
"StudentId": 3,
"StudentName": "Carol",
"StudentAge": 21
}
{
"_id": ObjectId("5c77a7a499b97a65744c1b53"),
"StudentId": 4,
"StudentName": "Carol",
"StudentAge": 26
}
{
"_id": ObjectId("5c77a7b499b97a65744c1b54"),
"StudentId": 5,
"StudentName": "Sam",
"StudentAge": 24
}
{
"_id": ObjectId("5c77a7c799b97a65744c1b55"),
"StudentId": 6,
"StudentName": "Mike",
"StudentAge": 27
}
{
"_id": ObjectId("5c77a7d399b97a65744c1b56"),
"StudentId": 7,
"StudentName": "Sam",
"StudentAge": 28
}
Example 1: Distinct Student Names
Get unique student names from the collection ?
db.distinctRecordDemo.distinct("StudentName");
["John", "Carol", "Sam", "Mike"]
Example 2: Distinct Student Ages
Get unique ages from the collection ?
db.distinctRecordDemo.distinct("StudentAge");
[21, 22, 26, 24, 27, 28]
Conclusion
The distinct() method efficiently retrieves unique values for any field, eliminating duplicates automatically. It returns an array containing only the distinct values found across all documents in the collection.
Advertisements
