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
MongoDB equivalent of `select distinct(name) from collectionName where age = "25"`?
To get the MongoDB equivalent of select distinct(name) from collectionName where age = "25", use the distinct() method with a field name and query condition. This returns unique values from the specified field that match the given criteria.
Syntax
db.collection.distinct("fieldName", { "conditionField": value })
Sample Data
db.distinctNameAndAgeDemo.insertMany([
{ "ClientFirstName": "John", "Age": 23 },
{ "ClientFirstName": "Larry", "Age": 25 },
{ "ClientFirstName": "David", "Age": 25 },
{ "ClientFirstName": "Carol", "Age": 26 },
{ "ClientFirstName": "Sam", "Age": 25 },
{ "ClientFirstName": "Larry", "Age": 25 },
{ "ClientFirstName": "Carol", "Age": 26 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd12759e3526dbddbbfb60b"),
ObjectId("5cd12768e3526dbddbbfb60c"),
ObjectId("5cd12773e3526dbddbbfb60d"),
ObjectId("5cd1277ee3526dbddbbfb60e"),
ObjectId("5cd12793e3526dbddbbfb60f"),
ObjectId("5cd127a3e3526dbddbbfb610"),
ObjectId("5cd127aae3526dbddbbfb611")
]
}
Display All Documents
db.distinctNameAndAgeDemo.find().pretty();
{
"_id": ObjectId("5cd12759e3526dbddbbfb60b"),
"ClientFirstName": "John",
"Age": 23
}
{
"_id": ObjectId("5cd12768e3526dbddbbfb60c"),
"ClientFirstName": "Larry",
"Age": 25
}
{
"_id": ObjectId("5cd12773e3526dbddbbfb60d"),
"ClientFirstName": "David",
"Age": 25
}
{
"_id": ObjectId("5cd1277ee3526dbddbbfb60e"),
"ClientFirstName": "Carol",
"Age": 26
}
{
"_id": ObjectId("5cd12793e3526dbddbbfb60f"),
"ClientFirstName": "Sam",
"Age": 25
}
{
"_id": ObjectId("5cd127a3e3526dbddbbfb610"),
"ClientFirstName": "Larry",
"Age": 25
}
{
"_id": ObjectId("5cd127aae3526dbddbbfb611"),
"ClientFirstName": "Carol",
"Age": 26
}
Get Distinct Names Where Age = 25
The following query is the MongoDB equivalent of select distinct(name) from collectionName where age = "25" ?
db.distinctNameAndAgeDemo.distinct("ClientFirstName", { "Age": 25 });
[ "Larry", "David", "Sam" ]
Key Points
- The
distinct()method automatically removes duplicates (notice "Larry" appears only once despite having two documents) - The second parameter is the query filter - only documents matching this condition are considered
- Results are returned as an array of unique values
Conclusion
MongoDB's distinct() method provides SQL-like distinct functionality. It returns unique field values that match the specified query condition, automatically filtering out duplicates.
Advertisements
