$toLong (Convert to 64-bit Integer)
Last updated: 2026-10-09
$toLong (Convert to 64-bit Integer)
$toLong converts a value to a 64-bit signed integer (BSON long), with a far wider range than int — ideal for timestamps, IDs and other large integers. It accepts numbers, numeric strings and booleans; null stays null. Typical uses: casting high-precision ID strings to numbers or handling second/millisecond timestamps. Strings must be integer literals. It is the $convert shortcut for to: long; mixing int and long in arithmetic auto-promotes to long.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toLong: <expression> }
⚙️ Parameters
| expression | A number, numeric string, or boolean. |
|---|
Returns:A long; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toLong: parse a timestamp string into a number
db.events.aggregate([
{ $project: {
ts: { $toLong: '$tsStr' }
} }
])
Output:
{ '_id': 1, 'ts': 1780000000000 }
📌 Notes
- 64-bit range comfortably holds millisecond timestamps
- Strings must be integer literals or the conversion throws
- Mixing int and long auto-promotes to long
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhen should I use $toLong?
AWhen values may exceed about 2.1 billion, such as timestamps and large IDs.
QWhat happens when mixed with $toInt?
AThe result auto-promotes to long.
QWhat does null return?
AIt returns null.