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
How to get distinct list of sub-document field values in MongoDB?
To get distinct list of sub-document field values in MongoDB, use the distinct() method with dot notation to access nested fields within arrays or embedded documents.
Syntax
db.collection.distinct("outerField.innerField");
Sample Data
Let us create a collection with student documents containing nested arrays ?
db.getDistinctListOfSubDocumentFieldDemo.insertMany([
{
"StudentId": 101,
"StudentPersonalDetails": [
{
"StudentName": "John",
"StudentAge": 24
},
{
"StudentName": "Carol",
"StudentAge": 21
}
]
},
{
"StudentId": 102,
"StudentPersonalDetails": [
{
"StudentName": "Carol",
"StudentAge": 26
},
{
"StudentName": "Bob",
"StudentAge": 21
}
]
},
{
"StudentId": 103,
"StudentPersonalDetails": [
{
"StudentName": "Bob",
"StudentAge": 25
},
{
"StudentName": "David",
"StudentAge": 24
}
]
}
]);
Example: Get Distinct Student Names
Query to get distinct student names from the nested array ?
db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName");
[ "Carol", "John", "Bob", "David" ]
Verify Sample Data
db.getDistinctListOfSubDocumentFieldDemo.find().pretty();
{
"_id" : ObjectId("..."),
"StudentId" : 101,
"StudentPersonalDetails" : [
{
"StudentName" : "John",
"StudentAge" : 24
},
{
"StudentName" : "Carol",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("..."),
"StudentId" : 102,
"StudentPersonalDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 26
},
{
"StudentName" : "Bob",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("..."),
"StudentId" : 103,
"StudentPersonalDetails" : [
{
"StudentName" : "Bob",
"StudentAge" : 25
},
{
"StudentName" : "David",
"StudentAge" : 24
}
]
}
Conclusion
Use distinct() with dot notation to extract unique values from nested array fields. MongoDB automatically flattens arrays and removes duplicates, returning distinct values from all matching sub-documents across the collection.
Advertisements
