Aggregation
db.orders.aggregate([
{ $match: { category: "Stationery" } },
{
$group: {
_id: null,
totalQuantity: { $sum: "$quantity" },
}
}
]);
We can get value of a field by using $fieldName
db.collection.aggregate([
{
$set: {
defaultUsername: {
$concat: ["$first_name", " ", "$last_name"]
}
}
}
]);
$match
Find documents that match certain condition.
$group
Group documents by a field name. It will return one document per unique key. The _id field specifies which field we're using to group the data.
{
$group: {
_id: "$city",
// group key
totalZips: { $count : { } }
// <field>: { <accumulator> : <expression> }
}
}
$sort
Sort documents in ascending/descending order by fields.
$limit
Limit amount of returned documents.
$project
Select fields for output document.
$set
Adds or modify fields on the pipeline.
$count
Count documents in the pipeline. Returns a document with only one field with the name that we set with the count output of the pipeline.
$out
Writes output documents of pipeline into another collection. Must be the last stage of the pipeline.