</>
Skip to content
MongoDB lessons (21/38)

MongoDB — Aggregation

Basic Aggregation

db.users.aggregate([
  { $match: { active: true } },
  { $group: { _id: "$country", count: { $sum: 1 } } }
])

Pipeline Stages

StageDescription
$matchFilter documents
$groupGroup documents
$sortSort documents
$projectReshape documents
$limitLimit results
$skipSkip documents
$lookupJoin collections
$unwindDeconstruct arrays

Examples

// Group by country
db.users.aggregate([
  { $group: { _id: "$country", count: { $sum: 1 } } }
])

// Average age by country
db.users.aggregate([
  { $group: { _id: "$country", avgAge: { $avg: "$age" } } }
])

// Sort by count
db.users.aggregate([
  { $group: { _id: "$country", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

Lookup (Join)

db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
    }
  }
])

Mini Practice

  1. Use $match and $group
  2. Calculate aggregates
  3. Sort results
  4. Use $lookup

Up Next

Continue with Aggregation Pipeline — pipeline details.

Related Topics

Frequently Asked Questions about Aggregation

What is Aggregation in MongoDB?

Aggregation is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Aggregation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Aggregation.

Why is Aggregation important in MongoDB?

Aggregation is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.