MongoDB Aggregation Pipelines

  1. $group — Groups documents by a field value/expression.
  2. $project- Selects a set of fields from the resulting output
  3. $match — Filters out the results.
  4. $limit / $skip— Paginate the documents
  5. $unwind — Expand arrays in documents
  6. $sort- Sorts the data
/* 1 */
{
"_id" : ObjectId("628a40d0265ae89785733873"),
"categoryId" : 2,
"productId" : 73,
"amount" : 300,
"orderDate" : ISODate("2022-05-20T08:00:00.000Z")
}
/* 2 */
{
"_id" : ObjectId("628a40ff265ae89785733892"),
"categoryId" : 2,
"productId" : 63,
"amount" : 456,
"orderDate" : ISODate("2022-05-21T08:00:00.000Z")
}
/* 3 */
{
"_id" : ObjectId("628a44db265ae897857338eb"),
"categoryId" : 3,
"productId" : 163,
"amount" : 496,
"orderDate" : ISODate("2022-05-15T08:00:00.000Z")
}
db.order.aggregate([
{
$match: {"categoryId" : 2}
},
{
$sort: { "orderDate" : -1}
},
{
$project : { "_id" : 0 , "productId" : 1 }
}
]);
/* 1 */
{
"productId" : 63
}
/* 2 */
{
"productId" : 73
}
db.order.aggregate([
{
$match: {}
},
{
$group:
{
"_id" : "$categoryId",
"products": { $push : "$productId"}

}
}

]);
/* 1 */
{
"_id" : 3,
"products" : [
163
]
}
/* 2 */
{
"_id" : 2,
"products" : [
73,
63
]
}
var groupStage = {
$group:
{
"_id" : "$categoryId",
"products": { $push : "$productId"}

}
};
db.order.aggregate([
{
$match: {}

},
groupStage

]);
/* 1 */
{
"_id" : ObjectId("629372e3265ae897857b6eff"),
"categoryId" : 23,
"brand" : "Samsung",
"model" : "DXV-LSI",
"tags" : [
"tv",
"samsung",
"led"
]
}
db.getCollection('product').aggregate([ { $unwind : "$tags"}]).pretty()
/* 1 */
{
"_id" : ObjectId("629372e3265ae897857b6eff"),
"categoryId" : 23,
"brand" : "Samsung",
"model" : "DXV-LSI",
"tags" : "tv"
}
/* 2 */
{
"_id" : ObjectId("629372e3265ae897857b6eff"),
"categoryId" : 23,
"brand" : "Samsung",
"model" : "DXV-LSI",
"tags" : "samsung"
}
/* 3 */
{
"_id" : ObjectId("629372e3265ae897857b6eff"),
"categoryId" : 23,
"brand" : "Samsung",
"model" : "DXV-LSI",
"tags" : "led"
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store