Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the number of items in an array in MongoDB?
To count the number of items in an array, you can use $size operator. The syntax is as follows:
db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).prett
y();
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
>db.getSizeOfArray.insertOne({"StudentId":1,"StudentName":"Larry","StudentMarks":[87,34,5
6,77,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebc536fd07954a4890680")
}
>db.getSizeOfArray.insertOne({"StudentId":2,"StudentName":"Sam","StudentMarks":[90,76,56
]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebc6b6fd07954a4890681")
}
>db.getSizeOfArray.insertOne({"StudentId":3,"StudentName":"Carol","StudentMarks":[90,76]})
;
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebc7a6fd07954a4890682")
}
Now you can display all documents from a collection with the help of find() method. The query is as follows:
> 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
]
}
The following is the query to count the number of items in an array:
>db.getSizeOfArray.aggregate({$project:{NumberOfItemsInArray:{$size:"$StudentMarks"}}}).p
retty();
The following is the output:
{ "_id" : ObjectId("5c6ebc536fd07954a4890680"), "NumberOfItemsInArray" : 6 }
{ "_id" : ObjectId("5c6ebc6b6fd07954a4890681"), "NumberOfItemsInArray" : 3 }
{ "_id" : ObjectId("5c6ebc7a6fd07954a4890682"), "NumberOfItemsInArray" : 2 }Advertisements