MongoDB -Aggregation
Hello guys, in our last story we learned, how to convert SQL queries into MongoDB. In this story, we are going to learn MongoDB Aggregation. Let’s start…!!!
Aggregation:-
- In MongoDB, Aggregation is an operation where we can process different types of collections and we can calculate results according to different conditions.
- We can perform different types of operations on group data to get a single result. As we all know the Count (*) in SQL and group by is the same as the Aggregation in MongoDB.
- We can use the Aggregate() method for aggregation in MongoDB. The basic syntax of the aggregate method is
>db.collection_name.aggregate(aggregate_operation)
1) Example :-
>db.class.find()
Output :- Here we get all records from class collection.
Now we can use an aggregate method to check the records by the group
>db.class.aggregate([{$group : {_id: “$type”, TotalRecords:{$sum :1}}}])
Output :- Here we get all records count in one line.
We can take another example for more understanding. We have a class collection of different books and authors.
2) Example :-
>db.class.find().pretty()
Output :- Here we get all records in a perticular format using pretty().
So from the above class collection, we can group by authors and total book count.
>db.class.aggregate([{$group : {_id : “$author” , TotalBook : {$sum :1}}}])
Output :- We got final result of total book and authors
As there are various types of Expressions which is used by Aggregate Function
i) $avg :- Used to calculate average values of a collection.
ii) $first :- To fetch the first document of the collection according to grouping.
iii) $sum :- Used to calculate the sum of every document of a collection.
iv) $addToSet :- Insert all values without duplicates records.
v) $min :- Will get minimum value from a collection.
vi) $max :- Used to find maximum value from a collection.
vii) $last :- To fetch the last document of a grouping collection.
In MongoDB, there are three different ways of performing aggregation.
A) The Aggregation Pipeline.
B) The Map-Reduce Function.
C) Single-purpose Aggregation methods.
A) Aggregation Pipeline :- That is a framework where document enters as an input in a multi-stages pipeline and using the framework the documents transferred into aggregated records.
B) Map-Reduce Function :- Map-Reduce function is used to reduce large volumes of data into useful sorted data. We can use map-reduce command for that which is in javascript.
C) Single-purpose Aggregation methods :- It has limited scope as compared to map-reduce and pipeline due to less complex. It provides you straight forward solution for common data sets.
If you have any queries. please feel free to ask. We will see more about MongoDB in the next story with more information. Thank You…
LinkedIn => https://www.linkedin.com/in/minakshee-bagul-4442b6184/