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
Does Mongo shell treats numbers as float by default.? How can we work it around explicitly?
Yes, MongoDB shell treats numbers as double (float) by default. To work with integers or other specific number types, you need to explicitly specify the type using MongoDB's type constructors like NumberInt(), NumberLong(), or NumberDecimal().
Syntax
NumberInt("value") // 32-bit integer
NumberLong("value") // 64-bit integer
NumberDecimal("value") // 128-bit decimal
Example: Creating Integer Array
Let's create an array with explicit integer values instead of floats ?
var integerArrayDemo = [
NumberInt("50"),
NumberInt("60"),
NumberInt("70"),
NumberInt("90"),
NumberInt("40")
];
Display Array with printjson()
printjson(integerArrayDemo);
[
NumberInt(50),
NumberInt(60),
NumberInt(70),
NumberInt(90),
NumberInt(40)
]
Display Array with print()
print(integerArrayDemo);
NumberInt(50),NumberInt(60),NumberInt(70),NumberInt(90),NumberInt(40)
Key Points
- MongoDB shell defaults to double precision floating point for all numbers.
- Use
NumberInt()for 32-bit integers,NumberLong()for 64-bit integers. -
printjson()shows formatted output,print()shows comma-separated values.
Conclusion
Always use explicit type constructors like NumberInt() when you need specific numeric types in MongoDB shell. This ensures data integrity and prevents unexpected floating-point behavior in your applications.
Advertisements
