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
Get count of array elements from a specific field in MongoDB documents?
To count array elements from a specific field, use $size in MongoDB. Let us create a collection with documents −
> db.demo723.insertOne({"Subject":["MySQL","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab094d43417811278f588a")
}
> db.demo723.insertOne({"Subject":["C"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab095243417811278f588b")
}
> db.demo723.insertOne({"Subject":["C++","Java","Python"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab095f43417811278f588c")
}
Display all documents from a collection with the help of find() method −
> db.demo723.find();
This will produce the following output −
{ "_id" : ObjectId("5eab094d43417811278f588a"), "Subject" : [ "MySQL", "MongoDB" ] }
{ "_id" : ObjectId("5eab095243417811278f588b"), "Subject" : [ "C" ] }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "Subject" : [ "C++", "Java", "Python" ] }
Following is the query to count array elements in MongoDB −
> db.demo723.aggregate([
... { $project: { count: { $size: '$Subject' } } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5eab094d43417811278f588a"), "count" : 2 }
{ "_id" : ObjectId("5eab095243417811278f588b"), "count" : 1 }
{ "_id" : ObjectId("5eab095f43417811278f588c"), "count" : 3 }Advertisements