- 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
How to add together a subset of elements of an array in MongoDB aggregation?
To add together a subset of elements of an array, use $first along with $sum. Let us create a collection with documents −
> db.demo610.insertOne({Values:[10,20,30,40,50]});{ "acknowledged" : true, "insertedId" : ObjectId("5e9747b8f57d0dc0b182d62e") }
Display all documents from a collection with the help of find() method −
> db.demo610.find().pretty()
This will produce the following output −
{ "_id" : ObjectId("5e9747b8f57d0dc0b182d62e"), "Values" : [ 10, 20, 30, 40, 50 ] }
Here is the query to add together a subset of elements of an array in MongoDB aggregation −
> db.demo610.aggregate([ ... {$unwind:"$Values"}, ... {$group:{"_id":"$_id", ... "1st":{$first:"$Values"}, ... "All":{$sum:"$Values"}}}, ... {$project:{"_id":"$_id", ... "SumOfAllMinus1":{$subtract:["$All","$1st"]}}}, ... {$group:{"_id":null, ... "SumOfAllExcept1stValue":{$sum:"$SumOfAllMinus1"}}} ... ])
This will produce the following output −
{ "_id" : null, "SumOfAllExcept1stValue" : 140 }
Advertisements