MongoDB Group By and Count Examples


Table of Contents

  1. Basic Group By and Count
  2. Group By Multiple Fields
  3. Group By with Conditions
  4. Group By with Multiple Aggregations
  5. 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!







Author Info:

Rakesh (He/Him) has a Masters Degree in Computer Science with over 15+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap