MongoDB $toLong Operator

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

What Is $toLong?

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

Remember
$toLong = convert value → 64-bit long

{ $toLong: <expression> }

doubles     → truncate toward 0
int strings → "100" OK; "2.5" ERROR
Date        → millis since epoch
true → 1, false → 0
null / missing → null

Bigger than int32? Prefer $toLong over $toInt
UsePrefer
64-bit whole numbers / large IDs$toLong
Small 32-bit counts$toInt
Convert with onError / onNull$convert

How to Use $toLong in MongoDB

Convert large ID or counter strings, then sort, compare, or filter.

  1. Choose an expression stage ($addFields or $project).
  2. Pass an integer string, number, or Date to $toLong.
  3. Optional: sort or match on the converted long.
  4. If strings may be invalid, prefer $convert with onError.
PieceRequired?Role
$toLongYesConvert expression → long (or null)
ExpressionYesInt string, number (truncated), bool, Date, or long
$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 Date:
        result = millisSinceEpoch(x)
    else if x is double/decimal:
        result = truncateTowardZero(x)   // must fit int64
    else if x is integer string / bool / int / long:
        result = long(x)
    else:
        error  // e.g. "2.5" string
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while converting to long integers.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toLong: <expression> }
Shorthand for{ $convert: { input: <e>, to: "long" } }
String example"3000000000" → Long("3000000000")
Truncation1.99999 → 1 (toward zero)
DateMilliseconds since Unix epoch
vs $toInt64-bit vs 32-bit; use long for large IDs

Live Preview

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

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

Result
input = "3000000000"
$toLong → Long("3000000000")

{ asLong: Long("3000000000") }

Worked Walkthrough — Large User IDs

Two users store IDs as strings. One ID is larger than a 32-bit int, so $toLong is the safe choice.

Calculation
Documents:
  { name: "Ada", userId: "3000000000" }   // > int32 max (~2.1e9)
  { name: "Bob", userId: "100" }

$toLong("3000000000") → Long("3000000000")
$toLong("100")        → Long("100")

Sort by convertedId descending:
  Ada → Bob

Note: $toInt("3000000000") would error (out of range)

MongoDB Examples

Insert sample users with string IDs, convert with $toLong, then sort. Run these in mongosh in order.

Example 1 — Sample Data

Two users store userId as an integer string. Ada’s ID is too large for $toInt.

mongosh
db.users.insertMany([
  { _id: 1, name: "Ada", userId: "3000000000" },
  { _id: 2, name: "Bob", userId: "100" }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.users.find()

Read the rows like this:

FieldExamplesPlain English
_id1, 2Document id
name"Ada", "Bob"Display name
userId"3000000000", "100"External ID stored as a string

How It Works

  1. Insert two users. insertMany stores simple documents for the lesson.
  2. IDs are strings. MongoDB does not auto-convert "3000000000" to a long on insert.
  3. Why long? 3000000000 is above the 32-bit int max (~2.1 billion).

Example 2 — Convert with $toLong

Goal: add a convertedId field as a 64-bit long for every user.

mongosh
db.users.aggregate([
  {
    $addFields: {
      convertedId: { $toLong: "$userId" }
    }
  }
]);

How It Works

  1. Read each userId string. Values come from Example 1.
  2. Convert to long. $toLong accepts base-10 integer strings, including values past int32.
  3. Numbers you can sort. convertedId is a real 64-bit integer, not text.
  4. Keep originals. $addFields adds convertedId without removing userId.

Example 3 — Sort by ID

Convert first, then sort highest ID first (Ada before Bob).

mongosh
db.users.aggregate([
  {
    $addFields: {
      convertedId: { $toLong: "$userId" }
    }
  },
  {
    $sort: { convertedId: -1 }
  }
]);

How It Works

  1. Same conversion. Stage one builds convertedId like Example 2.
  2. Sort on the long. $sort: { convertedId: -1 } orders numerically, highest first.
  3. Why convert first? Sorting raw strings can put "100" before "90"; longs compare by value.
  4. Ada first. 3000000000 is greater than 100.

Edge Cases & Pitfalls

Check these before using $toLong in production pipelines.

vs int

Use long when values may exceed int32

$toInt fails past ~2.1 billion. Prefer $toLong for large IDs and millisecond timestamps.

strings

"2.5" as a string fails

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

truncate

Doubles truncate, they do not round

1.99999 → 1. Use $round first if you need nearest-integer behavior.

date

Dates become milliseconds

$toLong on a Date returns millis since the Unix epoch—useful for numeric time math.

Performance Notes

ApproachCostBest for
$toLong per queryPer-document convertCleaning imported ID strings
Store Long / NumberLongCheapest long-termIDs and counters you sort often
$convert + onErrorSlightly more workDirty / nullable inputs

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

Key Takeaways

  • Role: convert a value to a 64-bit long integer.
  • vs $toInt: use long for values past ~2.1 billion.
  • Strings: whole integers only—"2.5" errors.
  • Dates: become milliseconds since the epoch.

One line: $toLong answers “turn this into a 64-bit whole number—safe for large IDs and millis.”

Frequently Asked Questions

$toLong converts a value to a 64-bit long integer inside an aggregation pipeline. Use it in stages such as $project and $addFields.
Use $toLong when values may exceed the 32-bit int range (about ±2.1 billion). Common cases include large IDs, Unix millisecond timestamps, and big counters.
$toLong is shorthand for { $convert: { input: <expr>, to: "long" } }. Use $convert with onError when invalid values should return a fallback instead of failing the pipeline.
$toLong truncates toward zero. For example, 1.99999 becomes 1. It does not round to the nearest integer.
No. String inputs must be base-10 integers such as "100" or "-2". Decimal-looking strings like "2.5" cause a conversion error.
$toLong returns null when the input is null or missing. It does not throw an error for null input.

Next: $toLower

Convert strings to lowercase in an aggregation pipeline.

$toLower 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