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 query to count the size of an array distinctly?
To count the size of an array distinctly in MongoDB, use the distinct() method to get unique elements and then apply .length to count them. This eliminates duplicate values and returns only the count of unique elements.
Syntax
db.collection.distinct('fieldName').length;
Sample Data
Let us create a collection with duplicate student names ?
db.countOrSizeDemo.insertMany([
{"StudentFirstName": "John"},
{"StudentFirstName": "David"},
{"StudentFirstName": "David"},
{"StudentFirstName": "Carol"},
{"StudentFirstName": "Sam"},
{"StudentFirstName": "John"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd304f5b64f4b851c3a13dc"),
ObjectId("5cd304fab64f4b851c3a13dd"),
ObjectId("5cd304fcb64f4b851c3a13de"),
ObjectId("5cd30500b64f4b851c3a13df"),
ObjectId("5cd30505b64f4b851c3a13e0"),
ObjectId("5cd3050ab64f4b851c3a13e1")
]
}
View All Documents
db.countOrSizeDemo.find();
{ "_id": ObjectId("5cd304f5b64f4b851c3a13dc"), "StudentFirstName": "John" }
{ "_id": ObjectId("5cd304fab64f4b851c3a13dd"), "StudentFirstName": "David" }
{ "_id": ObjectId("5cd304fcb64f4b851c3a13de"), "StudentFirstName": "David" }
{ "_id": ObjectId("5cd30500b64f4b851c3a13df"), "StudentFirstName": "Carol" }
{ "_id": ObjectId("5cd30505b64f4b851c3a13e0"), "StudentFirstName": "Sam" }
{ "_id": ObjectId("5cd3050ab64f4b851c3a13e1"), "StudentFirstName": "John" }
Example: Count Distinct Elements
Get the count of unique student names ?
db.countOrSizeDemo.distinct('StudentFirstName').length;
4
View Distinct Values
To see the actual distinct values before counting ?
db.countOrSizeDemo.distinct('StudentFirstName');
[ "Carol", "David", "John", "Sam" ]
Key Points
-
distinct()returns an array of unique values for the specified field. -
.lengthproperty gives the count of elements in the distinct array. - Duplicate values are automatically excluded from the count.
Conclusion
Use db.collection.distinct('fieldName').length to count unique array elements efficiently. This method eliminates duplicates and provides an accurate count of distinct values in your collection.
Advertisements
