MongoDB $toInt Operator

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

What You’ll Learn

The $toInt operator converts values to a 32-bit integer in MongoDB aggregation pipelines. Use it to parse whole-number strings, truncate decimals, and enable integer math on imported or mixed-type data.

01

Integer Conversion

Values to int32.

02

Syntax

One expression.

03

Truncation

Doubles → whole nums.

04

$project Stage

Parse qty fields.

05

Use Cases

Counts, IDs, imports.

06

vs $toLong

32-bit vs 64-bit.

Definition and Usage

In MongoDB’s aggregation framework, the $toInt operator converts an expression to a 32-bit signed integer. Imported data often stores quantities, counts, and IDs as strings like "42" or "100". $toInt parses those into whole numbers for sorting, counting, and integer arithmetic.

$toInt is shorthand for { $convert: { input: <expression>, to: "int" } }. When converting doubles, it truncates toward zero — so 3.9 becomes 3, not 4.

💡
Beginner Tip

Int32 range is roughly -2.1 billion to 2.1 billion. For larger whole numbers (like big user IDs or timestamps), use $toLong instead.

📝 Syntax

The $toInt operator takes one expression:

mongosh
{ $toInt: <expression> }

Literal Examples

mongosh
{ $toInt: "42" }
// Result: 42

{ $toInt: 3.9 }
// Result: 3 (truncates toward zero)

{ $toInt: -3.9 }
// Result: -3

{ $toInt: "$quantity" }
// Convert the quantity field

Conversion Rules

  • null — returns null.
  • Integer — returns the same int value (if within int32 range).
  • String — parses whole-number strings (invalid strings cause an error).
  • Double / Decimal — truncates toward zero to a whole number.
  • Booleantrue becomes 1, false becomes 0.
  • Range — int32: -2,147,483,648 to 2,147,483,647. Out-of-range values error.
  • Use inside $project, $addFields, $set, or $group.

💡 $toInt vs $toLong vs $toDouble

$toInt — 32-bit whole numbers; good for counts, quantities, small IDs
$toLong — 64-bit whole numbers; for large IDs and timestamps
$toDouble — floating point; when you need decimal fractions
Use $toInt when values fit in int32 and you need whole numbers only

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Syntax{ $toInt: <expression> }
Output type32-bit signed integer (int32)
Equivalent{ $convert: { input: <expr>, to: "int" } }
Double behaviorTruncates toward zero (3.9 → 3)
Common stages$project, $addFields, $group
String
{
  $toInt: "$quantity"
}

Parse text integer

Truncate
{
  $toInt: 3.9
}

Returns 3

Sum
{
  $sum: {
    $toInt: "$qty"
  }
}

Total quantities

Boolean
{
  $toInt: true
}

Returns 1

Examples Gallery

Parse string quantities, truncate doubles to whole numbers, sum inventory counts, and handle conversion safely with $convert.

📚 Inventory Quantities

Start with an inventory collection where quantities are stored as strings and convert them with $toInt.

Sample Input Documents

Suppose you have an inventory collection with string quantities from a CSV import:

mongosh
[
  { "_id": 1, "item": "Widget A", "quantity": "50" },
  { "_id": 2, "item": "Widget B", "quantity": "120" },
  { "_id": 3, "item": "Widget C", "quantity": "75" },
  { "_id": 4, "item": "Widget D", "quantity": "30" }
]

Example 1 — Convert String Quantity to Integer

Parse the quantity string into a 32-bit integer:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      quantity: 1,
      qtyInt: { $toInt: "$quantity" }
    }
  }
])

How It Works

$toInt parses whole-number strings into integers. Once converted, the field supports integer sorting, comparison, and arithmetic.

📈 Truncation and Aggregation

Truncate doubles, sum quantities, and filter by integer thresholds.

Example 2 — Truncate Double to Integer

When a field stores a decimal, $toInt truncates toward zero:

mongosh
db.metrics.aggregate([
  {
    $project: {
      value: 1,
      wholeNumber: { $toInt: "$value" }
    }
  }
])

// value: 3.9   → wholeNumber: 3
// value: -2.7  → wholeNumber: -2
// value: 10.0  → wholeNumber: 10

How It Works

$toInt does not round — it drops the fractional part. Use $round first if you need rounding before conversion.

Example 3 — Sum Quantities with $group

Convert string quantities and compute total stock:

mongosh
db.inventory.aggregate([
  {
    $group: {
      _id: null,
      totalStock: {
        $sum: { $toInt: "$quantity" }
      },
      itemCount: { $sum: 1 }
    }
  }
])

// totalStock: 275 (50 + 120 + 75 + 30)

How It Works

$sum requires numeric input. Wrapping each quantity in $toInt converts string values before summing.

Example 4 — Filter by Integer Threshold

Convert quantities, then find low-stock items:

mongosh
db.inventory.aggregate([
  {
    $addFields: {
      qtyInt: { $toInt: "$quantity" }
    }
  },
  {
    $match: {
      qtyInt: { $lt: 50 }
    }
  },
  {
    $project: {
      item: 1,
      qtyInt: 1
    }
  }
])

// Returns Widget D only (qtyInt: 30 < 50)

How It Works

Convert first, then filter. Comparing strings like "9" and "120" alphabetically would give wrong results.

Example 5 — Round Before Converting

When you need rounding instead of truncation:

mongosh
db.metrics.aggregate([
  {
    $project: {
      value: 1,
      truncated: { $toInt: "$value" },
      rounded: {
        $toInt: { $round: [ "$value", 0 ] }
      }
    }
  }
])

// value: 3.6
// truncated → 3
// rounded   → 4

How It Works

Combine $round with $toInt when you want nearest-integer behavior instead of truncation.

Bonus — Safe Conversion with $convert

When quantities may be invalid, use $convert with onError:

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      qtyInt: {
        $convert: {
          input: "$quantity",
          to: "int",
          onError: 0,
          onNull: 0
        }
      }
    }
  }
])

// "50"  → 50
// "N/A" → 0 (fallback)
// null  → 0

How It Works

$toInt errors on invalid strings. $convert with onError lets the pipeline continue with a safe default.

🚀 Use Cases

  • CSV/JSON import cleanup — parse string quantities and counts into integers.
  • Inventory management — sum stock levels and filter low-quantity items.
  • Counting and tallies — convert text counts for $sum and grouping.
  • Truncating decimals — drop fractional parts from double fields.
  • Schema migration — normalize legacy string-number fields in aggregation pipelines.

🧠 How $toInt Works

1

MongoDB reads the expression

The input resolves from a field path, numeric string, number, boolean, or nested expression.

Input
2

Value is converted to int32

Strings are parsed; doubles and decimals are truncated toward zero; booleans become 0 or 1.

Convert
3

An integer result is returned

The output supports $add, $sum, sorting, and integer comparisons.

Output
=

Whole number ready

Use in counts, sums, filters, and integer arithmetic pipelines.

Conclusion

The $toInt operator converts values to 32-bit integers in MongoDB aggregation pipelines. It is ideal for parsing whole-number strings, truncating decimals, and enabling integer math on mixed-type data.

For values outside the int32 range, use $toLong. For decimal fractions, use $toDouble. For conversions with error handling, use $convert. Next in the series: $toLong.

💡 Best Practices

✅ Do

  • Use $toInt for counts, quantities, and small whole numbers
  • Convert before $sum when fields are stored as strings
  • Use $round first when you need rounding, not truncation
  • Use $convert with onError for messy imported data
  • Switch to $toLong when values exceed int32 range

❌ Don’t

  • Expect $toInt to round (it truncates toward zero)
  • Use $toInt for large IDs beyond ~2.1 billion
  • Sort string numbers without converting first
  • Assume invalid strings will silently become zero (they error)
  • Use $toInt when you need decimal fractions

Key Takeaways

Knowledge Unlocked

Five things to remember about $toInt

Use these points when converting values to integers in MongoDB.

5
Core concepts
📝 02

{ $toInt: x }

One argument.

Syntax
🔢 03

Truncates

3.9 → 3.

Behavior
🛠 04

Parse & sum

String to int.

Usage
05

int32 limit

Use $toLong.

Range

❓ Frequently Asked Questions

$toInt converts a value to a 32-bit integer inside an aggregation pipeline. It is an aggregation expression operator used in stages like $project and $addFields.
The syntax is { $toInt: <expression> }. The expression can be a field reference like "$quantity", a numeric string, or another numeric expression.
$toInt truncates toward zero. For example, 3.9 becomes 3 and -3.9 becomes -3. It does not round to the nearest integer.
$toInt produces a 32-bit integer (range roughly -2.1 billion to 2.1 billion). $toLong produces a 64-bit integer for larger whole numbers. Use $toLong when values exceed the int32 range.
$toInt returns null when the input is null. It does not throw an error for null input.

Continue the Operator Series

Move on to $toLong for 64-bit integers, or review $convert for flexible type transforms.

Next: $toLong →

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