15

# Aggregation in MongoDB

Hi, today we are going to talk about aggregation in MongoDB.

aggregation basically allows us to process data records and we can do various operations and return the computed result. We can simply find a bunch of cool information about the data that is already inside our collection. It is a common task for any database so we must have look at it.

Imagine we have a collection of orders with the product name, price, buyer name properties. If you imagine its store you might know that a person can order multiple products and a product also can be ordered many times.

There are a lot of cool MongoDB functions available you can use to solve any problem. Suppose you want to know how many cameras have been sold or ordered. You can use count function for it like ordersCillection.count({catagory:”camera”}) so what we are telling this function is “we want to count inside this field that matches the word camera ”.this function will return an integer of how many cameras are there. How cool it was!

Let's see another one. Suppose we want to know all the products that are ordered but no duplicate names, we can use distinct for it. Like ordersCillection.distinct(‘name’) so what we are saying to this function? We just passed the field we want in return without any duplicates this function will return an array of all the product's names. Even though we have sold a product multiple times but we will find it only one time by distinct. It's pretty useful

Now let's talk about aggregation, suppose we want to find the total amount of money a customer has been spent. It sounds interesting right? Same can customer purchase multiple times so, how can we find the total amount of money each customer has spent.

We can use aggregate to solve this problem

ordersCillection.aggregate (

[

{$match: {} },

{$group: {_id: “$customerName”, total: {$sum: “$price”} } }

]

)

This syntax may not looks good. Let me explain it. At first, we put a match to a filter that we didn't used here. it is used if we dont wanna aggregate over everything in the collection in our case it's empty so we will aggregate over everything.

And into the 2nd line, we specified how we wanna group all the information together inside this group field may seems confusing let me explain it. We basically defining the structure of all the information we wanna get back. We are defining we need an id. As we know an id is something that identifies something its unique for each entries in every collection. And we filled the customer name to it so it will take all the matching customer name and count it as one

And the total filed will return to us with the sum of all the cost that particular id/person has spent

Aggregation is confusing sometimes we need more practice to capture it in our mind

15