MongoDB $toLong Operator

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

What You’ll Learn

The $toLong operator converts values to a 64-bit long integer in MongoDB aggregation pipelines. Use it for large user IDs, Unix millisecond timestamps, and any whole number that exceeds the 32-bit int range.

01

Long Conversion

Values to int64.

02

Syntax

One expression.

03

Large Numbers

Beyond int32 range.

04

$project Stage

Parse big IDs.

05

Use Cases

Timestamps, IDs.

06

vs $toInt

64-bit vs 32-bit.

Definition and Usage

In MongoDB’s aggregation framework, the $toLong operator converts an expression to a 64-bit signed long integer. While $toInt handles values up to about 2.1 billion, many real-world datasets store larger numbers — snowflake IDs, Unix timestamps in milliseconds, and high-volume counters all need the wider range that $toLong provides.

$toLong is shorthand for { $convert: { input: <expression>, to: "long" } }. Like $toInt, it truncates doubles toward zero when converting fractional numbers to whole numbers.

💡
Beginner Tip

JavaScript Date.now() returns milliseconds like 1718448600000 — too large for int32. Use $toLong for these timestamp values.

📝 Syntax

The $toLong operator takes one expression:

mongosh
{ $toLong: <expression> }

Literal Examples

mongosh
{ $toLong: "9876543210987" }
// Result: NumberLong(9876543210987)

{ $toLong: 1718448600000 }
// Result: NumberLong(1718448600000)

{ $toLong: "$userId" }
// Convert the userId field

{ $toLong: "$timestampMs" }
// Parse millisecond timestamp

Conversion Rules

  • null — returns null.
  • Long — returns the same long value.
  • String — parses whole-number strings (invalid strings cause an error).
  • Double / Decimal / Int — converts or truncates toward zero.
  • Booleantrue becomes 1, false becomes 0.
  • Range — int64: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • Use inside $project, $addFields, $set, or $group.

💡 $toLong vs $toInt

$toLong — 64-bit integer; up to ~9.2 quintillion; timestamps, snowflake IDs
$toInt — 32-bit integer; up to ~2.1 billion; counts, small quantities
Example: 1718448600000 (Unix ms) fits in long but overflows int32
See the $toInt operator tutorial for smaller whole numbers

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (type conversion)
Syntax{ $toLong: <expression> }
Output type64-bit signed integer (long / int64)
Equivalent{ $convert: { input: <expr>, to: "long" } }
Max value9,223,372,036,854,775,807
Common stages$project, $addFields, $group
Big ID
{
  $toLong: "$userId"
}

Large user ID

Timestamp
{
  $toLong: "$timestampMs"
}

Unix milliseconds

Sum
{
  $sum: {
    $toLong: "$views"
  }
}

Total large counts

Literal
{
  $toLong: "3000000000"
}

Beyond int32

Examples Gallery

Parse large user IDs, convert Unix millisecond timestamps, sum high-volume counters, and compare long vs int conversion limits.

📚 User Records

Start with a users collection where large IDs are stored as strings and convert them with $toLong.

Sample Input Documents

Suppose you have a users collection with snowflake-style IDs stored as strings:

mongosh
[
  {
    "_id": 1,
    "name": "Alice",
    "userId": "9876543210987",
    "lastSeenMs": "1718448600000"
  },
  {
    "_id": 2,
    "name": "Bob",
    "userId": "9876543210999",
    "lastSeenMs": "1718535000000"
  },
  {
    "_id": 3,
    "name": "Carol",
    "userId": "9876543211001",
    "lastSeenMs": "1718621400000"
  }
]

Example 1 — Convert Large String ID to Long

Parse the userId string into a 64-bit long integer:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      userId: 1,
      userIdLong: { $toLong: "$userId" }
    }
  }
])

How It Works

Values like 9876543210987 exceed the int32 maximum (~2.1 billion). $toLong handles them; $toInt would fail or overflow.

📈 Timestamps and Aggregations

Convert millisecond timestamps, sum large counters, and sort numerically.

Example 2 — Convert Unix Millisecond Timestamp

Parse timestamp strings that are too large for int32:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      lastSeenMs: 1,
      lastSeenLong: { $toLong: "$lastSeenMs" }
    }
  }
])

// "1718448600000" → NumberLong(1718448600000)
// Too large for $toInt (max ~2147483647)

How It Works

Unix timestamps in milliseconds are common in JavaScript and API data. They always need long (or double), not int32.

Example 3 — Sort by Numeric Timestamp

Convert timestamp strings, then sort by most recent activity:

mongosh
db.users.aggregate([
  {
    $addFields: {
      lastSeenLong: { $toLong: "$lastSeenMs" }
    }
  },
  {
    $sort: { lastSeenLong: -1 }
  },
  {
    $project: {
      name: 1,
      lastSeenLong: 1
    }
  }
])

How It Works

Sorting string timestamps alphabetically gives wrong order. Converting to long first ensures correct chronological sorting.

Example 4 — Sum Large View Counters

Aggregate page view counts stored as strings:

mongosh
db.analytics.aggregate([
  {
    $group: {
      _id: "$pageId",
      totalViews: {
        $sum: { $toLong: "$views" }
      }
    }
  },
  {
    $sort: { totalViews: -1 }
  }
])

// Sums view counts that may exceed int32 range

How It Works

High-traffic pages can accumulate billions of views. $toLong ensures the sum stays accurate without int32 overflow.

Example 5 — $toLong vs $toInt Overflow

See why large values need long instead of int:

mongosh
db.test.aggregate([
  {
    $project: {
      value: "3000000000",
      asLong: { $toLong: "3000000000" },
      asIntAttempt: {
        $convert: {
          input: "3000000000",
          to: "int",
          onError: "overflow"
        }
      }
    }
  }
])

// asLong:       NumberLong(3000000000) ✓
// asIntAttempt: "overflow" (exceeds int32 max of 2147483647)

How It Works

Three billion exceeds int32’s ~2.1 billion limit. $toLong handles it; $toInt fails or overflows.

Bonus — Safe Conversion with $convert

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

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      userIdLong: {
        $convert: {
          input: "$userId",
          to: "long",
          onError: 0,
          onNull: 0
        }
      }
    }
  }
])

// "9876543210987" → NumberLong(9876543210987)
// "invalid"       → 0 (fallback)
// null            → 0

How It Works

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

🚀 Use Cases

  • Snowflake and distributed IDs — parse large unique identifiers stored as strings.
  • Unix millisecond timestamps — convert Date.now() values for sorting and comparison.
  • High-volume counters — sum page views, event counts, and metrics beyond int32 range.
  • Data import cleanup — normalize large numeric strings from CSV or JSON imports.
  • Cross-system ID mapping — convert external system IDs that exceed 32-bit limits.

🧠 How $toLong 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 int64

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

Convert
3

A long integer is returned

The output supports $add, $sum, sorting, and comparisons on large whole numbers.

Output
=

Large whole number ready

Use for big IDs, timestamps, counters, and int64 arithmetic.

Conclusion

The $toLong operator converts values to 64-bit long integers in MongoDB aggregation pipelines. It is essential for snowflake IDs, Unix millisecond timestamps, and any whole number that exceeds the 32-bit int range.

For smaller whole numbers, $toInt is sufficient. For decimal fractions, use $toDouble. For conversions with error handling, use $convert. Next in the series: $toLower.

💡 Best Practices

✅ Do

  • Use $toLong for Unix millisecond timestamps
  • Choose long for snowflake IDs and large external identifiers
  • Convert before sorting string numbers or timestamps
  • Use $convert with onError for messy imported data
  • Prefer $toInt when values fit in the 32-bit range

❌ Don’t

  • Use $toInt for values above ~2.1 billion
  • Sort large numeric strings without converting first
  • Assume invalid strings will silently become zero (they error)
  • Use $toLong when you need decimal fractions
  • Forget that doubles are truncated toward zero, not rounded

Key Takeaways

Knowledge Unlocked

Five things to remember about $toLong

Use these points when converting values to long integers in MongoDB.

5
Core concepts
📝 02

{ $toLong: x }

One argument.

Syntax
🔢 03

Big numbers

IDs, timestamps.

Input
🛠 04

Sort & sum

Parse then use.

Usage
05

vs $toInt

64 vs 32 bit.

Range

❓ Frequently Asked Questions

$toLong converts a value to a 64-bit long integer inside an aggregation pipeline. It is an aggregation expression operator used in stages like $project and $addFields.
The syntax is { $toLong: <expression> }. The expression can be a field reference like "$userId", a numeric string, or another numeric expression.
Use $toLong when values exceed the 32-bit int range (roughly -2.1 billion to 2.1 billion). Common cases include large user 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 returns null when the input is null. It does not throw an error for null input.

Continue the Operator Series

Move on to $toLower for string case conversion, or review $toInt for 32-bit integers.

Next: $toLower →

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