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
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment