$add (Addition)
Last updated: 2026-10-09
$add (Addition)
$add performs addition inside aggregation expressions. It adds multiple numbers together, adds a number of milliseconds to a date, or returns a new date from a date plus milliseconds. It is commonly used in $project, $addFields, or $set to compute totals such as a price plus tax. Arguments are passed as an array with at least two elements; if any argument is null or missing, the whole expression returns null. To compute the millisecond difference between two dates, use $subtract instead.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $add: [ <expression1>, <expression2>, ... ] }
⚙️ Parameters
| operand | Numeric values, dates, or expressions resolving to them; at least two. |
|---|
Returns:The sum of the numbers; date plus milliseconds returns a date
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $add: compute total with tax
db.orders.aggregate([
{ $project: {
total: { $add: ['$price', '$tax'] }
} }
])
Output:
{ '_id': 1, 'total': 110 }
{ '_id': 2, 'total': 55 }
📌 Notes
- Any null or missing argument makes the whole expression null (guard with $ifNull)
- Date plus milliseconds returns a date; convert milliseconds to days by dividing by 86400000
- Unlike $sum (an accumulator used in $group), $add is a plain expression
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $add and $sum?
A$sum is an accumulator used in $group to sum values across documents; $add is a general expression that adds the values in an array.
QCan $add add days to a date?
ANot directly — the number is treated as milliseconds. Multiply by 86400000 first, or use $dateAdd with the day unit for clarity.
QWhat happens when $add meets null?
AIf any argument is null or missing the result is null; wrap with $ifNull when you need a default.