- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best way to sum array size fields in MongoDB?
To sum the array size fields, use $sum along with $size. Let us create a collection with documents −
> db.demo231.insertOne({"Subjects":["MongoDB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc73ff4cebbeaebec5143") } > db.demo231.insertOne({"Subjects":["Java","C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc757f4cebbeaebec5144") } > db.demo231.insertOne({"Subjects":["Python","Spring"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3fc762f4cebbeaebec5145") }
Display all documents from a collection with the help of find() method −
> db.demo231.find();
This will produce the following output −
{ "_id" : ObjectId("5e3fc73ff4cebbeaebec5143"), "Subjects" : [ "MongoDB", "MySQL", "SQL Server" ] } { "_id" : ObjectId("5e3fc757f4cebbeaebec5144"), "Subjects" : [ "Java", "C", "C++" ] } { "_id" : ObjectId("5e3fc762f4cebbeaebec5145"), "Subjects" : [ "Python", "Spring" ] }
Following is the query to sum array size fields in MongoDB −
> db.demo231.aggregate([{'$group': {'_id': '_id', 'ToTalValue': {'$sum': {'$size': '$Subjects'}}}}])
This will produce the following output −
{ "_id" : "_id", "ToTalValue" : 8 }
Advertisements