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.
Facing issues? Have Questions? Post them here! I am happy to answer!
- Program 3: Print the name of user as input - 1000+ Python Programs - Python-Programs
- 10 ways to Convert String to a Number in JavaScript - JavaScript
- How to Hum a Song to Google to find it out! [Android and iPhone] - Google
- How to empty trash in Android Device - Android
- How to Manage Profile Picture on Microsoft Teams - Teams
- How to open TextEdit from Mac Terminal - MacOS
- How to Copy full Absolute Path of a File on Mac - MacOS
- Python: pandas merge DataFrames on Common Column - Python