How to speed up $group phase in aggregation?

MongoDBDatabaseBig Data Analytics

To speed up the $group phase, use $group along with aggregation. Let us see an example and create a collection with documents −

> db.demo423.insertOne({"Information":[101,110,87,110,98,115,101,115,89,115]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e73a60e9822da45b30346e6")
}

Display all documents from a collection with the help of find() method −

> db.demo423.find();

This will produce the following output −

{ "_id" : ObjectId("5e73a60e9822da45b30346e6"), "Information" : [ 101, 110, 87, 110, 98, 115, 101, 115, 89, 115 ] }

Following is the query to speed up $group phase in aggregation −

> db.demo423.aggregate([
...    {
...       $project: {_id: 0, 'Information': 1}
...    },
...    {
...       $unwind: '$Information'
...    },
...    {
...       $group:{_id: '$Information', frequency:{$sum: 1}}
...    },
...    {
...       $sort:{frequency:-1}
...    },
...    {
...       $limit:2
...    }
... ])

This will produce the following output −

{ "_id" : 115, "frequency" : 3 }
{ "_id" : 110, "frequency" : 2 }
raja
Published on 03-Apr-2020 17:20:43
Advertisements