Table of Contents
- Basic Group By and Count
- Group By Multiple Fields
- Group By with Conditions
- Group By with Multiple Aggregations
- Group By with Sorting
In this section, we'll explore MongoDB's aggregation framework to perform group-by and count operations. These examples demonstrate how to use MongoDB's powerful querying capabilities directly in the database, without involving Java code.
Here are some common scenarios where you might use MongoDB's group by and count operations:
1. Basic Group By and Count
This example groups documents by a field and counts the occurrences:
db.users.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 } } }
])
This query groups users by their status and counts how many users are in each status.
2. Group By Multiple Fields
You can group by multiple fields to get more specific counts:
db.orders.aggregate([
{ $group: {
_id: { category: "$category", status: "$status" },
count: { $sum: 1 }
}
}
])
This query groups orders by both category and status and then counts the occurrences of each combination.
3. Group By with Conditions
You can add conditions to your grouping:
db.products.aggregate([
{ $match: { price: { $gt: 100 } } },
{ $group: { _id: "$category", count: { $sum: 1 } } }
])
This query first filters for products with a price greater than 100, then groups them by category and counts.
4. Group By with Multiple Aggregations
You can perform multiple aggregations in a single query:
db.sales.aggregate([
{ $group: {
_id: "$product",
totalQuantity: { $sum: "$quantity" },
averagePrice: { $avg: "$price" },
count: { $sum: 1 }
}
}
])
This query groups sales by product, and calculates the total quantity sold, average price, and count of sales for each product.
5. Group By with Sorting
You can sort the results of your group by operation:
db.visitors.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 5 }
])
This query groups visitors by country, counts them, sorts by count in descending order, and returns the top 5 countries.
These examples demonstrate the flexibility and power of MongoDB's aggregation framework for performing group-by and count operations. By leveraging these capabilities directly in MongoDB, you can offload complex data processing tasks from your application layer to the database, potentially improving performance and reducing network traffic.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!