Learn Python

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

MongoDB Introduction

MongoDB Setup

MongoDB DataBase

MongoDB Insert Data

MongoDB Read Document

MongoDB Update

MongoDB Delete

MongoDB Sorting Index

MongoDB Aggregation

MongoDB Mongodb with python

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

MongoDB aggregation

Aggregation

Using Aggregation you can pass a criteria for your query. Aggregation helps us to perform operations like max, count, sum, min, etc.

Syntax:
var pipeline=[ {.......}, {.......}, {.......} ] db.database_name.aggregate(pipeline,options)

What is pipeline?
The pipeline is an array, which means a sequence of data. In another word you can say the key element in aggregation as the pipeline.

What is options?
You can also pass Documents. So documents are options.

What are the valid aggregation stage?
1. $sum: this will calculate the sum of numeric values in a group.
2. $avg: this will calculate the average of numeric values in a group.
3. $max: this will find the maximum value in a group.
4. $min: this will finds the minimum value in a group.
5. $count: this will count the number of documents in a group.
6. $first: this will return the first value in a group.
7. $last: this will returns the last value in a group.
8. $addToSet: this will adds unique values to an array in a group.
9. $push: this will append values to an array in a group.
10. $group: this will group documents together based on the given key and will perform aggregation like min, max, sum, etc on the grouped data.
11. $match: it filters the documents based on the given condition.
12. $skip: this will skip the given number of documents and pass the remaining to the next stage.
13. $sort: this will sort the documents based on the given criteria.
14. $limit: this will limit the number of documents passed to the next stage.
15. $lookup: this is used to perform a left outer join on another collection and it will increases the input documents with the matched data.

Example:
Suppose you have a collection called sales. Here sales collection has document of transactions. Each document has fields like product, quantity, price, and date.

Now we need to do: 1. Filters the documents which comes in a specific date range. To do this you will use %match.
2. Make a group of the documents by product and also calculate the total quantity and total price of each product. To do this you can use $group.
3. Sorts the result by total quantity in descending order. To do this you will use $sort.
4. Limits the result to the top 5 products with the highest total quantity. To do this you will use $limit.
5. Reshapes the output by banning the id field and by renaming id to product. To do this you will use project.

Now let's see the practical code example:

Syntax:
db.sales.aggregate([
{ $match: { date: { $gte: ISODate("2023-01-01"), $lt: ISODate("2024-01-01") } } },#Match documents in a specific date range
{ $group: { _id: "$product", totalQuantity: { $sum: "$quantity" }, totalPrice: { $sum: { $multiply: ["$quantity", "$price"] } } } },# Group by product and calculate total quantity and total price
{ $sort: { totalQuantity: -1 } }, # Sort by total quantity in descending order
{ $limit: 5 }, #Limit the result to the top 5 products
{ $project: { _id: 0, product: "$_id", totalQuantity: 1, totalPrice: 1 } } #Reshape the output, excluding the id field and renaming id to product
])

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.