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
Count number of elements in an array with MongoDB?
To count the number of elements in an array in MongoDB, use the $size operator within the aggregation framework. The $size operator returns the number of elements in the specified array field.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $size: "$arrayField" }
}
}
]);
Sample Data
Let us create a sample collection with array data ?
db.countNumberOfElementsDemo.insertOne({
"UserMessage": ["Hi", "Hello", "Bye", "Awesome"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cef8ec2ef71edecf6a1f6a1")
}
Display the document to verify the data ?
db.countNumberOfElementsDemo.find().pretty();
{
"_id": ObjectId("5cef8ec2ef71edecf6a1f6a1"),
"UserMessage": [
"Hi",
"Hello",
"Bye",
"Awesome"
]
}
Count Array Elements
Use the $size operator to count elements in the UserMessage array ?
db.countNumberOfElementsDemo.aggregate([
{
$project: {
NumberOfElements: { $size: "$UserMessage" }
}
}
]);
{
"_id": ObjectId("5cef8ec2ef71edecf6a1f6a1"),
"NumberOfElements": 4
}
Key Points
- The
$sizeoperator only works with arrays, not with other data types. - Use the
$projectstage in aggregation to include the count result. - The array field must be prefixed with
$to reference the field value.
Conclusion
The $size operator in MongoDB's aggregation framework provides an efficient way to count array elements. Combine it with $project to return the count alongside other document fields.
Advertisements
