Syntax error How to group nested fields in MongoDB aggregation with count value in array?

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 }
Updated on: 2020-03-30T11:22:07+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements