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

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 30-Mar-2020 14:49:26
Advertisements