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 aggregate $slice to get the length of the array
To get the length of an array in MongoDB using aggregation, use the $size operator within a $project stage. 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 collection with documents ?
db.demo382.insertOne({
"Name": "David",
"details": [
{
"SubjectName": "MySQL"
},
{
"SubjectName": "MongoDB"
},
{
"SubjectName": "Java"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5b5e1c22064be7ab44e7f0")
}
Display all documents from the collection ?
db.demo382.find().pretty();
{
"_id": ObjectId("5e5b5e1c22064be7ab44e7f0"),
"Name": "David",
"details": [
{
"SubjectName": "MySQL"
},
{
"SubjectName": "MongoDB"
},
{
"SubjectName": "Java"
}
]
}
Example: Get Array Length Using $size
The following query uses aggregation to get the length of the details array ?
db.demo382.aggregate([
{ "$match": { "Name": "David" } },
{ "$project": { "count": { "$size": "$details" } } }
]);
{ "_id": ObjectId("5e5b5e1c22064be7ab44e7f0"), "count": 3 }
Key Points
- The
$sizeoperator only works with array fields and returns the number of elements. - Use
$matchto filter documents before counting if needed. - The result includes the
_idfield by default unless explicitly excluded.
Conclusion
The $size operator in MongoDB aggregation pipeline efficiently counts array elements. Combine it with $project to return only the count value for each matching document.
Advertisements
