Aggregation in mongodb is refered as the process of performing different type of operation on multiple documents with in a collection. This is done by using pipeline, which is made up of different stages. A stage output is input for another stage.
Different type of Aggregation pipeline:
$match : It is a operation which filters documents based on specified criteria.
example:
const Channel = await User.aggregate([
{
$match:{
username: username?.toLowerCase()
}
},
$lookup : performs a left outer join to a collection in the same database. The $lookup
stage adds a new array field to each input document. The new array field contains the matching documents from the "joined" collections. The $lookup
passes these reshaped stage to next stage.
{
$lookup:
{
from: "subscriptions", //select from the collection
localField: "_id", // localfield of the collection
foreignField: "channel", // foreignfield of the collection
as: "subscribers" // Name of the returned collection
}
},
$addFields: $addFields
add new fields to the output output document that contains all the existing field from the input document
{
$addFields:{
subscribersCount:{
$size : "$subscribers"
},
channelSubscribedToCount:{
$size:"$subscribedTo"
},
isSubscribedTo:{
$cond:{
if:{$in:[req.user?._id,"subscribers.subscriber"]}
then:true,
else:false
}
}
}
}
In this example, $cond
is adds field with some computation and condition.
$project: it passes the document with the requested fields to the next stage in the pipeline. The field can be existing fields from the input document or newly computed fields
{
$project:{
fullName:1,
usename:1,
email:1,
subscriberCount:1
}
}
In $project
1 represents that it should pass these fields which have 1.
A big big thank you Hitesh Choudhary sir , who made a video on aggregation pipeline in hindi.