
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
Speed Up Group Phase in Aggregation
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 }
Advertisements