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
How to insert LONG numbers in MongoDB?
To insert LONG numbers in MongoDB, use NumberLong(). This constructor handles 64-bit integers that exceed JavaScript's safe integer range, ensuring precise storage without data loss.
Syntax
db.collection.insert({
field: NumberLong("large_number_as_string")
});
Sample Data
Let us create a collection with documents containing large numbers ?
db.demo273.insertMany([
{
Name: "Robert",
id: NumberLong("100000000000001"),
isActive: true
},
{
Name: "David",
id: NumberLong("98888888888888888"),
isActive: false
},
{
Name: "Mike",
id: NumberLong("999999999999"),
isActive: true
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Example
Display all documents from the collection ?
db.demo273.find();
Output
This will produce the following output ?
{ "_id": ObjectId("5e4824df1627c0c63e7dbac3"), "Name": "Robert", "id": NumberLong("100000000000001"), "isActive": true }
{ "_id": ObjectId("5e4824e01627c0c63e7dbac4"), "Name": "David", "id": NumberLong("98888888888888888"), "isActive": false }
{ "_id": ObjectId("5e4824e11627c0c63e7dbac5"), "Name": "Mike", "id": NumberLong("999999999999"), "isActive": true }
Key Points
-
NumberLong()accepts a string parameter to avoid JavaScript number precision issues. - Without NumberLong(), large numbers may be truncated or stored incorrectly.
- Essential for storing Unix timestamps, user IDs, or any 64-bit integer values.
Conclusion
Use NumberLong() constructor with string parameters to store 64-bit integers in MongoDB. This ensures precise storage of large numbers without JavaScript's floating-point precision limitations.
Advertisements
