$trunc (Truncate)
Last updated: 2026-10-09
$trunc (Truncate)
$trunc truncates the fractional part of a number toward zero, optionally keeping a specified number of decimal places. It takes the value and an optional place argument with the same rules as $round. It is used to drop cents, prepare display values, or paginate. Unlike $round it never rounds up: 2.9 becomes 2 and -2.9 becomes -2. For positives $trunc matches $floor, but for negatives they diverge: -1.2 becomes -1 with $trunc and -2 with $floor.
| Category | Math |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $trunc: [ <value>, <place> ] }
⚙️ Parameters
| numeric value | A numeric value or an expression resolving to one. |
|---|---|
| position | Optional decimal places; 0 or omitted rounds to an integer, negative values round to tens or higher. |
Returns:The truncated value; null when null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $trunc: drop the fractional part of amounts
db.orders.aggregate([
{ $project: {
whole: { $trunc: '$price' }
} }
])
Output:
{ '_id': 1, 'whole': 19 }
{ '_id': 2, 'whole': 12 }
📌 Notes
- Always cuts toward zero without rounding
- Differs from $floor on negatives: $trunc(-1.2) is -1
- The place argument accepts negatives to round to tens or hundreds
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do $trunc and $floor differ on negatives?
A$trunc cuts toward zero (-1.2 becomes -1) while $floor goes toward negative infinity (-1.2 becomes -2).
QHow do $trunc and $round differ?
A$trunc simply drops the fraction while $round rounds at the .5 boundary.
QCan $trunc keep decimal places?
AYes, the second argument sets the places, so $trunc: [19.999, 2] gives 19.99.