MongoDB $trunc Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
Math

What You’ll Learn

The $trunc operator truncates numeric values toward zero to a chosen number of decimal places inside MongoDB aggregation pipelines. Use it when you need to chop extra digits without rounding up — for example, limiting display precision or applying strict billing rules.

01

Truncate

Chop, don’t round.

02

place Arg

Decimals or tens.

03

Toward Zero

Positive & negative.

04

$project

Add truncated fields.

05

vs $round

Trunc vs round.

06

Null Safety

Know null behavior.

Definition and Usage

In MongoDB’s aggregation framework, the $trunc operator removes digits beyond a specified decimal place without rounding. It always truncates toward zero. For example, truncating 21.578 to two places gives 21.57 (where $round would give 21.58).

This is useful when business rules require dropping fractional digits rather than rounding, such as conservative billing, fixed-precision exports, or display formatting where rounding would change totals unexpectedly.

💡
Beginner Tip

Think of $trunc like cutting off digits with scissors — it never rounds up. For standard rounding, use $round. For always rounding down, use $floor.

📝 Syntax

The $trunc operator accepts an array of two expressions:

mongosh
{ $trunc: [ <number>, <place> ] }

Alternatively, you can use the object form:

mongosh
{
  $trunc: {
    input: <number expression>,
    place: <place expression>
  }
}

Syntax Rules

  • First operand — the number to truncate (field path, literal, or expression).
  • Second operand (place) — how many decimal places to keep.
  • place: 2 — keep two decimal places by truncating the rest (e.g. 21.578 → 21.57).
  • place: 0 — truncate to a whole number toward zero.
  • Negative place — truncate to tens, hundreds, etc. (-1 → nearest 10 toward zero).
  • Use inside $project, $addFields, or $set.
  • If the number is null, the result is null.

💡 $trunc vs $round vs $floor

21.578, place 2$trunc21.57, $round21.58
-3.7, place 0$trunc-3, $floor-4
4.9, place 0$trunc4, $round5
Need standard rounding? → use $round
See the $round operator and $floor operator tutorials

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (arithmetic)
Syntax{ $trunc: [ number, place ] }
BehaviorTruncates toward zero (no rounding up)
OutputTruncated number (or null)
Common stages$project, $addFields, $set
2 decimals
{
  $trunc: ["$price", 2]
}

Chop after 2nd decimal

Integer
{
  $trunc: ["$score", 0]
}

Whole number toward zero

Nearest 100
{
  $trunc: ["$sales", -2]
}

place: -2

Null input
null

Returns null

Examples Gallery

Truncate sensor readings, compare with $round, handle negative values, and limit computed averages with $trunc.

📚 Sensor & Price Data

Truncate readings to two decimal places without rounding up.

Sample Input Documents

Suppose you have a readings collection:

mongosh
[
  { "_id": 1, "sensor": "Temp-A", "value": 21.578 },
  { "_id": 2, "sensor": "Temp-B", "value": 18.942 },
  { "_id": 3, "sensor": "Temp-C", "value": -3.789 }
]

Example 1 — Truncate to Two Decimal Places

Limit precision without rounding:

mongosh
db.readings.aggregate([
  {
    $project: {
      sensor: 1,
      value: 1,
      truncatedValue: {
        $trunc: ["$value", 2]
      }
    }
  }
])

How It Works

place: 2 keeps two digits after the decimal and drops the rest. Unlike $round, 21.578 becomes 21.57, not 21.58.

📈 Trunc vs Round & Negatives

Understand how $trunc differs from other numeric operators.

Example 2 — Compare $trunc and $round

See the difference on the same values:

mongosh
db.products.aggregate([
  {
    $project: {
      price: 1,
      truncated: { $trunc: ["$price", 2] },
      rounded: { $round: ["$price", 2] }
    }
  }
])

// price: 49.999 → truncated: 49.99, rounded: 50.00
// price: 29.451 → truncated: 29.45, rounded: 29.45

How It Works

When the next digit would cause a round-up, $trunc and $round diverge. Choose based on whether your business rule allows rounding or requires chopping digits.

Example 3 — Negative Numbers Truncate Toward Zero

$trunc behaves differently from $floor on negatives:

mongosh
db.readings.aggregate([
  {
    $project: {
      value: 1,
      truncated: { $trunc: ["$value", 0] },
      floored: { $floor: "$value" }
    }
  }
])

// value: -3.7 → truncated: -3, floored: -4
// value:  4.9 → truncated: 4,  floored: 4

How It Works

$trunc always moves toward zero. This matters for signed decimals like temperature below freezing, altitude, or financial adjustments.

Example 4 — Truncate a Computed Average

Truncate the result of a division expression:

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      total: { $sum: "$amount" },
      count: { $sum: 1 }
    }
  },
  {
    $project: {
      avgOrder: {
        $trunc: [
          { $divide: ["$total", "$count"] },
          2
        ]
      }
    }
  }
])

// total: 100, count: 3 → avgOrder: 33.33 (not 33.34 from rounding)

How It Works

The first argument can be any numeric expression. Here, $divide computes the average and $trunc limits precision without rounding up.

Example 5 — Truncate Sales to Nearest Hundred

Use a negative place for coarse buckets:

mongosh
db.stores.aggregate([
  {
    $project: {
      store: 1,
      monthlySales: 1,
      salesTruncated: {
        $trunc: ["$monthlySales", -2]
      }
    }
  }
])

// monthlySales: 1234.56 → salesTruncated: 1200
// monthlySales: 1999.99 → salesTruncated: 1900

How It Works

place: -2 truncates to the hundreds place toward zero. Unlike $round, values just below a boundary stay in the lower bucket.

Bonus — Conservative Billing (Truncate Tax)

Truncate tax instead of rounding up when rules require it:

mongosh
db.invoices.aggregate([
  {
    $project: {
      item: 1,
      subtotal: 1,
      taxTruncated: {
        $trunc: [
          { $multiply: ["$subtotal", 0.0825] },
          2
        ]
      },
      taxRounded: {
        $round: [
          { $multiply: ["$subtotal", 0.0825] },
          2
        ]
      }
    }
  }
])

// subtotal: 19.99 → tax at 8.25%:
//   raw: 1.649175
//   taxTruncated: 1.64
//   taxRounded:   1.65

How It Works

Multiply first, then truncate. This pattern shows why operator choice matters in financial pipelines.

🚀 Use Cases

  • Display precision — limit decimal places in dashboards without rounding up.
  • Conservative billing — truncate tax or fees when rules forbid rounding up.
  • Data export — produce fixed-precision numbers for CSV or API consumers.
  • Reporting buckets — snap values to tens or hundreds by truncating, not rounding.
  • Signed data — truncate toward zero on negative readings and balances.

🧠 How $trunc Works

1

MongoDB evaluates both operands

The pipeline resolves the number and the place value to numbers (or null).

Input
2

Digits beyond place are dropped

Extra decimal digits are removed toward zero. No rounding-up step occurs.

Truncate
3

The truncated number is returned

The result is stored in your projected field for display or further math.

Output
=

Precision-limited number

Use when chopping digits is required instead of standard rounding.

Conclusion

The $trunc operator truncates numeric values toward zero to a specified decimal place in MongoDB aggregation pipelines. It is the right choice when you need to drop extra digits without rounding up.

Remember: positive place for decimals, zero for whole numbers, negative for tens and hundreds. Compare with $round and $floor before choosing. Next in the series: $type.

💡 Best Practices

✅ Do

  • Use $trunc when business rules forbid rounding up
  • Compare output with $round on sample data before deploying
  • Test with positive, negative, and zero values
  • Truncate at the end of calculations (multiply/divide first)
  • Keep raw values in storage; truncate in projections for display

❌ Don’t

  • Assume $trunc rounds — it chops digits toward zero
  • Use $trunc when standard rounding is required (use $round)
  • Confuse $trunc with $floor on negative numbers
  • Use $trunc as a query filter (it is expression-only)
  • Forget that null input returns null

Key Takeaways

Knowledge Unlocked

Five things to remember about $trunc

Use these points when limiting numeric precision in pipelines.

5
Core concepts
📝 02

[ n, place ]

Two operands.

Syntax
🛠 03

vs $round

21.578 → 21.57.

Compare
04

Negatives

-3.7 → -3.

Edge case
🗃 05

Expressions OK

Not just fields.

Input

❓ Frequently Asked Questions

$trunc removes digits beyond a specified decimal place without rounding. It truncates toward zero, so 21.578 with place 2 becomes 21.57, not 21.58.
The array syntax is { $trunc: [ <number>, <place> ] }. You can also use { $trunc: { input: <expression>, place: <expression> } }. Use inside $project, $addFields, or $set.
$trunc chops extra digits toward zero without rounding up. $round uses standard rounding rules, so 21.578 at place 2 becomes 21.57 with $trunc but 21.58 with $round.
$trunc moves toward zero. For example, -3.7 at place 0 becomes -3. $floor would return -4 because it rounds toward negative infinity.
If the number expression resolves to null, $trunc returns null. It does not throw an error.

Continue the Operator Series

Move on to $type for BSON type inspection, or review $round for standard rounding.

Next: $type →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful