What is Aggregation Pipeline in MongoDB?

Published: (December 14, 2025 at 09:47 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for What is Aggregation Pipeline in MongoDB?

Aggregation Overview

Aggregation in MongoDB is the process of performing various operations on multiple documents within a collection. It uses pipelines composed of different stages, where the output of one stage becomes the input for the next.

Types of Aggregation Pipelines

$match

Filters documents. Works like a find() query but as a step in a multi‑stage pipeline.

const channel = await User.aggregate([
  {
    $match: {
      username: username?.toLowerCase()
    }
  },
  // …other stages
]);

$lookup

Performs a left outer join between two collections in the same database, merging data from a foreign collection into documents of a local collection.

{
  $lookup: {
    from: 'subscriptions',
    localField: '_id',
    foreignField: 'channel',
    as: 'subscribers'
  }
},
{
  $lookup: {
    from: 'subscriptions',
    localField: '_id',
    foreignField: 'subscriber',
    as: 'subscribedTo'
  }
},

$addFields (alias: $set)

Adds new fields to documents or overwrites existing ones while preserving all other fields.

{
  $addFields: {
    subscribersCount: { $size: '$subscribers' },
    channelsSubscribedToCount: { $size: '$subscribedTo' },
    isSubscribed: {
      $cond: {
        if: { $in: [req.user?._id, '$subscribers.subscribers'] },
        then: true,
        else: false
      }
    }
  }
}

$cond is a ternary operator that implements if‑then‑else logic within aggregation pipelines.

$project

Selects which fields to pass to the next stage and can also create or rename fields.

{
  $project: {
    fullName: 1,
    username: 1,
    subscribersCount: 1,
    channelsSubscribedToCount: 1,
    isSubscribed: 1,
    avatar: 1,
    coverImage: 1,
    email: 1
  }
}

Aggregation pipeline example

Back to Blog

Related posts

Read more »