Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
988998985857575789to988998985857575808due 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.
Advertisements
