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
Count the number of items in an array in MongoDB?
To count the number of items in an array in MongoDB, you can use the $size operator within the $project stage of an aggregation pipeline. The $size operator returns the number of elements in a specified array field. The syntax is −
db.yourCollectionName.aggregate({
$project: {
anyFieldName: { $size: "$yourArrayName" }
}
}).pretty();
Creating a Sample Collection
To understand the above syntax, let us create a collection with documents. Each document contains a StudentMarks array with a different number of elements ?
db.getSizeOfArray.insertOne({
"StudentId": 1,
"StudentName": "Larry",
"StudentMarks": [87, 34, 56, 77, 89, 90]
});
db.getSizeOfArray.insertOne({
"StudentId": 2,
"StudentName": "Sam",
"StudentMarks": [90, 76, 56]
});
db.getSizeOfArray.insertOne({
"StudentId": 3,
"StudentName": "Carol",
"StudentMarks": [90, 76]
});
Now display all documents from the collection using the find() method −
db.getSizeOfArray.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c6ebc536fd07954a4890680"),
"StudentId" : 1,
"StudentName" : "Larry",
"StudentMarks" : [ 87, 34, 56, 77, 89, 90 ]
}
{
"_id" : ObjectId("5c6ebc6b6fd07954a4890681"),
"StudentId" : 2,
"StudentName" : "Sam",
"StudentMarks" : [ 90, 76, 56 ]
}
{
"_id" : ObjectId("5c6ebc7a6fd07954a4890682"),
"StudentId" : 3,
"StudentName" : "Carol",
"StudentMarks" : [ 90, 76 ]
}
Counting Array Items Using $size
The following query uses the $size operator to count the number of items in the StudentMarks array for each document −
db.getSizeOfArray.aggregate({
$project: {
NumberOfItemsInArray: { $size: "$StudentMarks" }
}
}).pretty();
The following is the output −
{
"_id" : ObjectId("5c6ebc536fd07954a4890680"),
"NumberOfItemsInArray" : 6
}
{
"_id" : ObjectId("5c6ebc6b6fd07954a4890681"),
"NumberOfItemsInArray" : 3
}
{
"_id" : ObjectId("5c6ebc7a6fd07954a4890682"),
"NumberOfItemsInArray" : 2
}
Larry has 6 marks in the array, Sam has 3, and Carol has 2. The $size operator correctly returns the count for each document's array.
Conclusion
Use the $size operator within a $project aggregation stage to count the number of items in an array field in MongoDB. The operator takes the array field name prefixed with $ and returns the element count for each document.
