0
0
MongodbConceptBeginner · 3 min read

Number Type in MongoDB: Explanation and Usage

In MongoDB, the number type refers to numeric data stored in documents, including integers and floating-point values. MongoDB supports several numeric types like int32, int64, and double to handle different sizes and precision of numbers.
⚙️

How It Works

Think of the number type in MongoDB as the way you store any kind of number in your database, just like writing numbers on paper. MongoDB has different number types to fit different needs, like small numbers, big numbers, or numbers with decimals.

For example, int32 is like a small box that holds whole numbers up to about 2 billion, while int64 is a bigger box that can hold much larger whole numbers. The double type is like a box that can hold numbers with decimals, such as 3.14 or 0.001.

This variety helps MongoDB store numbers efficiently and accurately depending on what you need, just like choosing the right size container for your stuff at home.

💻

Example

This example shows how to insert different number types into a MongoDB document and then retrieve it.

javascript
db.products.insertOne({
  name: "Gadget",
  quantity: NumberInt(100),
  price: NumberDouble(19.99),
  bigNumber: NumberLong("9007199254740991")
});

const product = db.products.findOne({ name: "Gadget" });
printjson(product);
Output
{ "_id" : ObjectId("..."), "name" : "Gadget", "quantity" : 100, "price" : 19.99, "bigNumber" : NumberLong("9007199254740991") }
🎯

When to Use

Use number types in MongoDB whenever you need to store numeric data like counts, prices, measurements, or IDs. Choose int32 for smaller whole numbers to save space, int64 for very large whole numbers, and double when you need decimals.

For example, an online store might use int32 for product stock counts, double for product prices, and int64 for tracking large user IDs or timestamps.

Key Points

  • MongoDB supports multiple number types: int32, int64, and double.
  • Choose the number type based on size and precision needs.
  • Use NumberInt(), NumberLong(), and NumberDouble() helpers to specify types explicitly.
  • Numbers are stored efficiently to optimize space and performance.

Key Takeaways

MongoDB stores numbers using different types for size and precision: int32, int64, and double.
Use int32 for smaller whole numbers and int64 for very large whole numbers.
Use double when you need to store decimal numbers.
Explicitly specify number types with NumberInt(), NumberLong(), and NumberDouble() when inserting data.
Choosing the right number type helps save space and keeps data accurate.