Skip to content

Expressions & Computed Fields

Aggregation expressions calculate new values from existing fields.

Adds fields without removing existing fields.

db.products.aggregate([
{
$addFields: {
priceWithTax: { $multiply: ["$price", 1.18] }
}
}
])
db.products.aggregate([
{
$project: {
name: 1,
finalPrice: { $subtract: ["$price", "$discount"] },
_id: 0
}
}
])
db.users.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
emailLower: { $toLower: "$email" }
}
}
])
db.orders.aggregate([
{
$project: {
totalAmount: 1,
orderSize: {
$cond: [
{ $gte: ["$totalAmount", 5000] },
"large",
"normal"
]
}
}
}
])
db.orders.aggregate([
{
$project: {
year: { $year: "$createdAt" },
month: { $month: "$createdAt" },
dayOfWeek: { $dayOfWeek: "$createdAt" }
}
}
])
db.orders.aggregate([
{
$addFields: {
itemCount: { $size: "$items" },
firstItem: { $arrayElemAt: ["$items", 0] }
}
}
])
db.orders.aggregate([
{
$project: {
totalAsString: { $toString: "$totalAmount" },
roundedTotal: { $round: ["$totalAmount", 2] }
}
}
])