Web Programming TutorialsLearn about the Aggregation Method in MongoDB

Learn about the Aggregation Method in MongoDB

In this chapter, we are going to explore the ‘aggregate’ method to operate on the documents present inside a collection of MongoDB. This method collects the records from the collection’s document to process and return a single result such as sum, count, max, min, avg, etc.

Aggregation in MongoDB
If we talk about RDBMS, then aggregate functions are those which process the records based on certain criteria and compute the result such as ‘count (*)’ function to count the number of rows in a table. In the similar manner, the ‘aggregate’ method in MongoDB helps group together the values from multiple documents present inside a collection to perform various operations on the grouped data which returns a single result such as number of occurrence of a record across multiple documents in a collection.

The ensureIndex () Method
In MongoDB, we use the ‘aggregate ()’ method to perform various aggregation operations. The following is the basic syntax for the ‘aggregate ()’ method in MongoDB.

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Example
The following is an example on using the ‘aggregate ()’ method. Let’s insert 4 documents into a collection known as ‘aggregate_demo_db’.

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\Aparajita>cd C:\Program Files\MongoDB\Server\3.2\bin

C:\Program Files\MongoDB\Server\3.2\bin>mongo.exe
MongoDB shell version: 3.2.10
connecting to: test
> use aggregate_demo_db
switched to db aggregate_demo_db
> db.aggregate_demo_db.save ( [ {
... title: 'MongoDB Tutorials', description: 'A complete guide on MongoDB', author: 'Elite Team',
... website: 'https://www.eduonix.com/', tags: ['MongoDB', 'DB', 'NoSQL'], downloads: 465899 },{
... title: 'PHP Tutorials', description: 'A complete guide on PHP7', author: 'Technical Team',
... website: 'https://www.eduonix.com/', tags: ['language', 'website', 'development'], downloads: 5435 },{
... title: 'NodeJS Tutorials', description: 'A complete guide on NodeJS', author: 'NodeJS Team',
... website: 'https://www.eduonix.com/', tags: ['nodejs', 'website', 'next_generation','JavaScript'], downloads: 8760 }, {
... title: 'Angular 2 Tutorials',  description: 'A complete guide on Angular 2', author: 'Angular 2 team',
... website: 'https://www.eduonix.com/', tags: ['angularJS', 'angular2', 'website','JavaScript'], downloads: 7500} ])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.aggregate_demo_db.find()
{ "_id" : ObjectId("5856f1e76b1b219fe0a63ad0"), "title" : "MongoDB Tutorials", "description" : "A complete guide on MongoDB", "author" : "Elite Team", "website" : "https://www.eduonix.com/", "tags" : [ "MongoDB", "DB", "NoSQL" ], "downloads" : 465899 }
{ "_id" : ObjectId("5856f1e76b1b219fe0a63ad1"), "title" : "PHP Tutorials", "description" : "A complete guide on PHP7", "author" : "Technical Team", "website" : "https://www.eduonix.com/", "tags" : [ "language", "website", "development" ], "downloads" : 5435 }
{ "_id" : ObjectId("5856f1e76b1b219fe0a63ad2"), "title" : "NodeJS Tutorials", "description" : "A complete guide on NodeJS", "author" : "NodeJS Team", "website" : "https://www.eduonix.com/", "tags" : [ "nodejs", "website", "next_generation", "JavaScript" ], "downloads" : 8760 }
{ "_id" : ObjectId("5856f1e76b1b219fe0a63ad3"), "title" : "Angular 2 Tutorials", "description" : "A complete guide on Angular 2", "author" : "Angular 2 team", "website" : "https://www.eduonix.com/", "tags" : [ "angularJS", "angular2", "website", "JavaScript" ], "downloads" : 7500 }
>

mongo
Explanation of the code

  • Here, we are using ‘aggregate_demo_db’ as the collection name of MongoDB.
  • Next, we are using the ‘save ()’ method to insert four records together as the bulk write operation in the MongoDB.
  • Lastly, we are using the ‘aggregate ([{$group: {_id: “$website”, total_tutorial: {$sum: 1}}}])’ method to calculate the number of occurrences of website URL across all documents present in collection ‘aggregate_demo_db’.
  • Since, the website URL occurres 4 times ‘https://www.eduonix.com/’ when we inserted 4 records in the collection. Therefore, the criteria given the aggregate function will return the count as 4 as shown below.

mongo-2
Note: – In the above example, we have grouped documents by field website which is present in all the four documents which we inserted in the collection ‘aggregate_demo_db’. If we compare the above operation with that of RDBMS databases like Oracle, DB2, MySQL, etc. then it will be equivalent to the following SQL.

Select website, count(*) from aggregate_demo_db.table_name group by website;

Aggregation Expressions in MongoDB
There are total 8 aggregation expressions available in MongoDB. They are described along with an example as follows.

S No.

Aggregation Expression

Description

Example

1.

$sum

This expression is used to sum up the defined value from all documents present inside a particular collection in MongoDB.

db.demo.aggregate ([{$group : {_id : “$website”, total_tutorial : {$sum : “$downloads”}}}])

2.

$avg

This expression is used to calculate the average of all given values from all the documents present inside a collection.

db.demo.aggregate ([{$group : {_id : “$website”, total_tutorial : {$avg : “$downloads”}}}])

3.

$min

This expression is used to get the minimum of the corresponding values from all documents present inside a collection.

db.demo.aggregate([{$group : {_id : “$website”, total_tutorial : {$min : “$downloads”}}}])

4.

$max

This expression is used to get the maximum of the corresponding values from all documents present inside a collection.

db.demo.aggregate([{$group : {_id : “$website”, total_tutorial : {$max : “$downloads”}}}])

5.

$push

This expression is used to insert the value to an array in the resulting document.

db.demo.aggregate([{$group : {_id : “$author”, website : {$push: “$website”}}}])

6.

$addToSet

This expression is used to insert the value to an array in the resulting document but does not create duplicates.

db.demo.aggregate([{$group : {_id : “$author “, website : {$addToSet : “$website”}}}])

7.

$first

This expression is used to get the first document from the source documents according to the grouping. Usually, this makes sense when it is used together with some previously applied “$sort”-stage.

db.demo.aggregate([{$group : {_id : “$author “, first_url : {$first : “$website”}}}])

8.

$last

This expression is used to get the last document from the source documents according to the grouping. Usually, this makes sense when it is used together with some previously applied “$sort”-stage.

db.demo.aggregate([{$group : {_id : “$author”, last_url : {$last : “$website”}}}])

Conclusion:
In this chapter, we have learnt about the practical use of the ‘aggregate ()’ method with the help of multiple examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -