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 count of array elements from a specific field in MongoDB documents?
To count array elements from a specific field in MongoDB, use the $size operator within an aggregation pipeline. This operator returns the number of elements in an array field for each document.
Syntax
db.collection.aggregate([
{ $project: { count: { $size: "$arrayFieldName" } } }
]);
Sample Data
db.demo723.insertMany([
{"Subject": ["MySQL", "MongoDB"]},
{"Subject": ["C"]},
{"Subject": ["C++", "Java", "Python"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eab094d43417811278f588a"),
ObjectId("5eab095243417811278f588b"),
ObjectId("5eab095f43417811278f588c")
]
}
View Sample Data
db.demo723.find();
{ "_id": ObjectId("5eab094d43417811278f588a"), "Subject": ["MySQL", "MongoDB"] }
{ "_id": ObjectId("5eab095243417811278f588b"), "Subject": ["C"] }
{ "_id": ObjectId("5eab095f43417811278f588c"), "Subject": ["C++", "Java", "Python"] }
Example: Count Array Elements
Count the number of subjects for each document ?
db.demo723.aggregate([
{ $project: { count: { $size: "$Subject" } } }
]);
{ "_id": ObjectId("5eab094d43417811278f588a"), "count": 2 }
{ "_id": ObjectId("5eab095243417811278f588b"), "count": 1 }
{ "_id": ObjectId("5eab095f43417811278f588c"), "count": 3 }
Conclusion
The $size operator efficiently counts array elements within aggregation pipelines. It returns the exact number of elements in the specified array field for each document in the collection.
Advertisements
