
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to group nested fields in MongoDB aggregation with count value in array?
At first, let us create a collection with documents −
> db.demo99.insertOne( ... { ... ... 'Details': ... { ... 'X': ... { ... 'Values': [10,30,50], ... 'Number':3, ... }, ... 'Y': ... { ... 'Values': [1000, 180], ... 'Number': 2, ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d91eab8903cdd865577b9") } > db.demo99.insertOne( ... { ... ... 'Details': ... { ... 'X': ... { ... 'Values': [100,300,500,6000], ... 'Number':4, ... }, ... 'Y': { ... 'Values': [10, 20,60], ... 'Number': 3, ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d927bb8903cdd865577ba") }
Display all documents from a collection with the help of find() method −
> db.demo99.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d91eab8903cdd865577b9"), "Details" : { "X" : { "Values" : [ 10, 30, 50 ], "Number" : 3 }, "Y" : { "Values" : [ 1000, 180 ], "Number" : 2 } } } { "_id" : ObjectId("5e2d927bb8903cdd865577ba"), "Details" : { "X" : { "Values" : [ 100, 300, 500, 6000 ], "Number" : 4 }, "Y" : { "Values" : [ 10, 20, 60 ], "Number" : 3 } } }
Following is the query to group nested fields in aggregation with count value in array −
> db.demo99.aggregate([ { $project: { Count: { $objectToArray: "$Details" } } }, { $unwind: "$Count" }, { $group: { _id: "$Count.k", count: { $sum: "$Count.v.Number"} } } ])
This will produce the following output −
{ "_id" : "Y", "count" : 5 } { "_id" : "X", "count" : 7 }
- Related Questions & Answers
- Count by multiple fields with MongoDB aggregation
- MongoDB query to group several fields using aggregation framework?
- How to match and group array elements with the max value in MongoDB aggregation?
- Aggregation: group date in nested documents (nested object) and display the count?
- How to compare two fields in aggregation filter with MongoDB?
- MongoDB aggregation to combine or merge fields and then count?
- Aggregation in MongoDB for nested documents?
- MongoDB aggregation framework with group query example?
- MongoDB aggregation group and remove duplicate array values?
- Match between fields in MongoDB aggregation framework?
- Group all documents with common fields in MongoDB?
- MongoDB query to replace value with aggregation?
- MongoDB query to get only specific fields in nested array documents?
- MongoDB Increment value inside nested array?
- MongoDB aggregation with equality inside array?
Advertisements