What is Aggregation Pipeline in MongoDB?
Source: Dev.to

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
}
}
}
}
$condis a ternary operator that implementsif‑then‑elselogic 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
}
}
