MongoDB $toInt Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toInt?

$toInt is a MongoDB aggregation expression that converts a value to a 32-bit integer. It is shorthand for { $convert: { input: <expr>, to: "int" } }.

Remember
$toInt = convert value → 32-bit int

{ $toInt: <expression> }

doubles     → truncate toward 0 (3.9 → 3)
int strings → "5" OK; "2.5" ERROR
true → 1, false → 0
null / missing → null
out of int32 range → error

Need bigger ints? Use $toLong
UsePrefer
32-bit whole numbers$toInt
Larger whole numbers$toLong
Convert with onError / onNull$convert

How to Use $toInt in MongoDB

Convert quantity strings (or mixed types), then multiply, sum, or filter.

  1. Choose an expression stage ($addFields or $project).
  2. Pass an integer string or number to $toInt.
  3. Optional: multiply by price or sort on the converted int.
  4. If strings may be invalid, prefer $convert with onError.
PieceRequired?Role
$toIntYesConvert expression → int (or null)
ExpressionYesInt string, number (truncated), bool, or int
$convertNoSame conversion with error/null handling

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null or missing:
        result = null
    else if x is double/decimal:
        result = truncateTowardZero(x)   // must fit int32
    else if x is integer string / bool / int:
        result = int(x)
    else:
        error  // e.g. "2.5" string
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting to integers.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toInt: <expression> }
Shorthand for{ $convert: { input: <e>, to: "int" } }
String example"5" → 5; "2.5" → error
Truncation1.99999 → 1 (toward zero)
Booleantrue → 1, false → 0
Range32-bit int; use $toLong if larger

Live Preview

Pick an input and see the int-style result (browser demo of the same idea).

Simulates $toInt rules: integer strings OK, doubles truncate, decimal strings error.

Result
input = "5"
$toInt → 5

{ asInt: 5 }

Worked Walkthrough — Quantity × Price

Quantity is stored as the string "5" with price 10. Convert, then multiply for the line total.

Calculation
Document:
  { item: "apple", qty: "5", price: 10 }

$toInt("5") → 5

total = qty × price
      = 5 × 10
      = 50

Check: 5 apples at $10 each = $50 ✓

MongoDB Examples

Insert sample orders with string quantities, convert with $toInt, then compute line totals. Run these in mongosh in order.

Example 1 — Sample Data

Two orders store qty as an integer string (common with imported CSV/JSON).

mongosh
db.orders.insertMany([
  { _id: 1, item: "apple", qty: "5", price: 10 },
  { _id: 2, item: "pie", qty: "10", price: 20 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read the rows like this:

FieldExamplesPlain English
_id1, 2Document id
item"apple", "pie"Product name
qty"5", "10"Quantity stored as a string
price10, 20Unit price (number)

How It Works

  1. Insert two orders. insertMany stores simple documents for the lesson.
  2. Quantities are strings. MongoDB does not auto-convert "5" to an int on insert.
  3. Ready to convert. The next example turns those strings into integers.

Example 2 — Convert with $toInt

Goal: add a convertedQty field as a 32-bit integer for every order.

mongosh
db.orders.aggregate([
  {
    $addFields: {
      convertedQty: { $toInt: "$qty" }
    }
  }
]);

How It Works

  1. Read each qty string. Values come from Example 1.
  2. Convert to int. $toInt accepts base-10 integer strings like "5".
  3. Numbers you can multiply. convertedQty is a real integer, not text.
  4. Keep originals. $addFields adds convertedQty without removing qty.

Example 3 — Line Total

Convert the quantity, then multiply by price for each line total.

mongosh
db.orders.aggregate([
  {
    $addFields: {
      convertedQty: { $toInt: "$qty" }
    }
  },
  {
    $project: {
      item: 1,
      totalPrice: {
        $multiply: ["$convertedQty", "$price"]
      }
    }
  }
]);

How It Works

  1. Same conversion. Stage one builds convertedQty like Example 2.
  2. Multiply. $multiply does 5 × 10 = 50 and 10 × 20 = 200.
  3. Project a slim result. $project keeps item and totalPrice.
  4. Why convert first? Multiplying a string quantity would fail or behave unexpectedly—convert, then calculate.

Edge Cases & Pitfalls

Check these before using $toInt in production pipelines.

strings

"2.5" as a string fails

String inputs must be whole integers. Use $toDouble first (then $toInt), or $convert with onError.

truncate

Doubles truncate, they do not round

3.9 → 3 and -3.9 → -3. Use $round first if you need nearest-integer behavior.

range

Stay inside int32

Values outside the 32-bit range error. Prefer $toLong for larger whole numbers.

null

Null and missing become null

$toInt returns null for null/missing inputs—it does not become zero.

Performance Notes

ApproachCostBest for
$toInt per queryPer-document convertCleaning imported qty strings
Store intsCheapest long-termFields you multiply/sum often
$convert + onErrorSlightly more workDirty / nullable inputs

Prefer storing integer types when you control writes. Converting on every read is fine for cleanup, but avoid repeated string→int work on hot paths.

Key Takeaways

  • Role: convert a value to a 32-bit integer.
  • Doubles: truncate toward zero (not round).
  • Strings: whole integers only—"2.5" errors.
  • Bigger ints: use $toLong.

One line: $toInt answers “turn this into a 32-bit whole number I can count and multiply.”

Frequently Asked Questions

$toInt converts a value to a 32-bit integer inside an aggregation pipeline. Use it in stages such as $project and $addFields.
$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 (about ±2.1 billion). $toLong produces a 64-bit integer for larger whole numbers.
$toInt is shorthand for { $convert: { input: <expr>, to: "int" } }. Use $convert with onError when invalid values should return a fallback instead of failing the pipeline.
No. String inputs must be base-10 integers such as "5" or "-2". Decimal-looking strings like "2.5" cause a conversion error.
$toInt returns null when the input is null or missing. It does not throw an error for null input.

Next: $toLong

Convert values to 64-bit integers in an aggregation pipeline.

$toLong tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful