Using Aggregations in MongoDB

 Using aggregations in MongoDB allows you to process and transform data from your collections through a pipeline of operations. Aggregation is commonly used for tasks such as grouping, filtering, calculating averages/sums, or transforming documents.


Here’s a breakdown of how to use aggregation pipelines in MongoDB.


๐Ÿ”ง Basic Syntax

javascript

Copy

Edit

db.collection.aggregate([

  { stage1 },

  { stage2 },

  ...

])

Each stage in the array performs a transformation on the data.


๐Ÿ“˜ Common Aggregation Stages

Stage Description

$match Filters documents (like a find query)

$group Groups documents by a field and performs aggregations (e.g., sum, avg)

$project Includes, excludes, or reshapes document fields

$sort Sorts documents

$limit Limits the number of documents

$skip Skips a specified number of documents

$lookup Performs a left outer join with another collection

$unwind Deconstructs an array field to output multiple documents

$addFields Adds new fields or modifies existing ones


๐Ÿงฎ Example Aggregation: Group by Category and Count

javascript

Copy

Edit

db.products.aggregate([

  { $group: {

      _id: "$category",

      total: { $sum: 1 }

  }}

])

This groups documents in the products collection by the category field and counts how many products are in each category.


๐Ÿ“Š Example: Average Price by Category

javascript

Copy

Edit

db.products.aggregate([

  { $group: {

      _id: "$category",

      avgPrice: { $avg: "$price" }

  }}

])

๐Ÿ”— Example with $match and $group

javascript

Copy

Edit

db.orders.aggregate([

  { $match: { status: "shipped" } },

  { $group: {

      _id: "$customerId",

      totalSpent: { $sum: "$amount" }

  }}

])

This filters orders with status: "shipped" and then groups them by customerId, summing the amount each customer spent.


๐Ÿช„ Example with $lookup (Join)

javascript

Copy

Edit

db.orders.aggregate([

  {

    $lookup: {

      from: "customers",

      localField: "customerId",

      foreignField: "_id",

      as: "customerInfo"

    }

  }

])

This joins orders with customers based on the customerId field.

Learn MERN Stack Course in Hyderabad

Read More

Creating Relationships in MongoDB using Mongoose

API Rate Limiting with Express

Logging with Morgan and Winston

Error Handling in Express.js

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?