Expressions & Computed Fields
Expressions & Computed Fields
Section titled “Expressions & Computed Fields”Aggregation expressions calculate new values from existing fields.
$addFields
Section titled “$addFields”Adds fields without removing existing fields.
db.products.aggregate([ { $addFields: { priceWithTax: { $multiply: ["$price", 1.18] } } }])$project With Computed Fields
Section titled “$project With Computed Fields”db.products.aggregate([ { $project: { name: 1, finalPrice: { $subtract: ["$price", "$discount"] }, _id: 0 } }])String Expressions
Section titled “String Expressions”db.users.aggregate([ { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, emailLower: { $toLower: "$email" } } }])Conditional Expressions
Section titled “Conditional Expressions”db.orders.aggregate([ { $project: { totalAmount: 1, orderSize: { $cond: [ { $gte: ["$totalAmount", 5000] }, "large", "normal" ] } } }])Date Expressions
Section titled “Date Expressions”db.orders.aggregate([ { $project: { year: { $year: "$createdAt" }, month: { $month: "$createdAt" }, dayOfWeek: { $dayOfWeek: "$createdAt" } } }])Array Expressions
Section titled “Array Expressions”db.orders.aggregate([ { $addFields: { itemCount: { $size: "$items" }, firstItem: { $arrayElemAt: ["$items", 0] } } }])Convert Types
Section titled “Convert Types”db.orders.aggregate([ { $project: { totalAsString: { $toString: "$totalAmount" }, roundedTotal: { $round: ["$totalAmount", 2] } } }])