Difference between NumberLong(x) and NumberLong("x") in MongoDB?

The NumberLong(x) function can lose precision with very large integers due to JavaScript's number limitations, while NumberLong("x") preserves exact precision by accepting the number as a string.

Syntax

NumberLong(number)        // May lose precision for very large values
NumberLong("string")      // Preserves exact precision

Example

Let us create a collection with documents to demonstrate the difference ?

db.demo603.insertMany([
    {"longValue": NumberLong(988998985857575789)},
    {"longValueInString": NumberLong("988998985857575789")}
]);
{
  "acknowledged": true,
  "insertedIds": [
    ObjectId("..."),
    ObjectId("...")
  ]
}

Display all documents from the collection ?

db.demo603.find().pretty();
{
  "_id": ObjectId("5e9605e5ed011c280a0905d1"),
  "longValue": NumberLong("988998985857575808")
}
{
  "_id": ObjectId("5e9605faed011c280a0905d2"),
  "longValueInString": NumberLong("988998985857575789")
}

Key Points

  • Notice the longValue changed from 988998985857575789 to 988998985857575808 due to precision loss.
  • The longValueInString preserved the exact value 988998985857575789.
  • JavaScript's Number type has a maximum safe integer limit of 2^53-1, causing rounding errors beyond this range.

Conclusion

Always use NumberLong("string") for large integers to preserve precision. The string format prevents JavaScript's number limitations from affecting your data accuracy in MongoDB.

Updated on: 2026-03-15T03:48:22+05:30

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements