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
MongoDB aggregation to sum individual properties on an object in an array across documents
For this, use aggregate() in MongoDB. Let us first create a collection with documents −
> db.demo131.insertOne(
... {
... "_id": 101,
... "Details": [
... {
... "PlayerScore": 500,
... "PlayerName": "Chris"
... },
... {
... "PlayerScore": 400,
... "PlayerName": "David"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo131.insertOne(
... {
... "_id": 102,
... "Details": [
... {
... "PlayerScore": 600,
... "PlayerName": "Chris"
... },
... {
... "PlayerScore": 200,
... "PlayerName": "David"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo131.find();
This will produce the following output −
{ "_id" : 101, "Details" : [ { "PlayerScore" : 500, "PlayerName" : "Chris" }, { "PlayerScore" : 400, "PlayerName" : "David" } ] }
{ "_id" : 102, "Details" : [ { "PlayerScore" : 600, "PlayerName" : "Chris" }, { "PlayerScore" : 200, "PlayerName" : "David" } ] }
Following is the query to sum individual properties on an object in an array −
> db.demo131.aggregate([
... { $unwind: "$Details" },
... {
... $group: {
... _id:"$Details.PlayerName",
... Value:{$sum:"$Details.PlayerScore"}
... }
... },
... {
... $group: {
... _id: 0,
... Details:{ $push: {Details:"$_id",Value:"$Value"}}
... }
... },
... {
... $project:{Details:1,_id:0}
... } ])
This will produce the following output −
{ "Details" : [ { "Details" : "David", "Value" : 600 }, { "Details" : "Chris", "Value" : 1100 } ] }Advertisements