Skip to content
LESSON 09 / 50Intermediatebson storage

BSON Data Types: Decimal128, Int64, and UTC Dates

Master BSON numeric fidelity and temporal types, avoiding IEEE 754 floating point rounding corruption in financial systems using Decimal128.

Interactive Engine Simulator

BSON Binary Byte Layout Inspector

Explore how MongoDB serializes JSON documents into binary BSON with length headers for O(1) field navigation.

BSON Total Size
61 bytes
Incl. 4B header & 1B \0
Elements Count
4 fields
Type tagged
Field Traversal
O(1) Jump
Via length headers
Max Document Size
16 MB
Hard engine limit
Document Byte Stream (Click to inspect field)
Header:
3d 00 00 00
(4-byte little-endian int32 total length)
0x07"_id":ObjectId (12 bytes)
075f69640065e31f8a3b...(17 B)
0x02"name":UTF-8 String
026e616d65000b000000...(21 B)
0x10"age":32-bit Integer
10616765001d000000(9 B)
0x08"active":Boolean
086163746976650001(9 B)
Terminator:
00
(1-byte null terminator 0x00)
0x07

Field "_id" • ObjectId (12 bytes)

17 Bytes total

ObjectId: 4-byte timestamp, 5-byte random value, 3-byte incrementing counter.

Why BSON over JSON? JSON is text-based and requires full stream parsing ($O(N)$) to find an inner property. BSON embeds length headers for each document and string, letting WiredTiger jump directly to the target byte offset in $O(1)$ time.

1. Formal Definition & Architecture Intent

BSON provides strict numeric and temporal types unavailable in standard JSON: 32-bit integer (Int32), 64-bit integer (Int64), IEEE 754-2008 128-bit decimal floating point (Decimal128), and 64-bit millisecond UTC Date timestamps.

2. Explain Like I'm 5 (Mental Model)

Computers calculate standard decimals (like 0.1 + 0.2) in binary, resulting in 0.30000000000000004. In a bank ledger, those lost cents send people to jail. Decimal128 calculates numbers in exact base-10 decimal math, eliminating floating-point rounding errors completely.

3. Real-World Architecture Example

Financial ledger transaction recording precise fractional currency balances.

Sample BSON Documents:
Collection: db.transactions
{
  "_id": "tx_1001",
  "account_id": "acc_772",
  "amount": "NumberDecimal(\"1099.99\")",
  "shares": "NumberDecimal(\"14.5029182374\")",
  "created_at": "ISODate(\"2026-03-01T15:30:00.123Z\")"
}

Decimal128 provides 34 decimal digits of precision, avoiding rounding errors inherent in 64-bit binary floats.

4. MQL Implementation Steps

Step 1: Demonstrate floating-point bug vs Decimal128 fix
// ❌ Binary float rounding flaw:
0.1 + 0.2 === 0.3; // returns false! (0.30000000000000004)

// ✅ Exact Decimal128 precision:
NumberDecimal("0.1") + NumberDecimal("0.2"); // returns NumberDecimal("0.3")
Always pass strings to NumberDecimal("...") to prevent JS pre-parsing float errors.
Step 2: Query records matching Decimal128 exact values
db.transactions.find({ amount: NumberDecimal("1099.99") });
Strict numeric equality check on Decimal128.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Decimal12834 decimal digits of precision, range 10^-6143 to 10^6144. Essential for financial balances.
NumberLong (Int64)64-bit signed integer. Necessary for counters or IDs exceeding 2^31 - 1 (2,147,483,647).
ISODate64-bit integer representing milliseconds since Unix epoch (Jan 1, 1970 UTC).

6. Deep Dive: JavaScript 64-bit Float Trap in Node.js & Mongo Shell

JavaScript numbers are all double-precision 64-bit IEEE 754 floats. Any integer greater than Number.MAX_SAFE_INTEGER (9,007,199,254,740,991) loses precision. In Node.js or the mongosh shell, always construct Long or Decimal using string literals: Long.fromString("9223372036854775807") to avoid silent bit truncation.

// ⚠️ Silent corruption trap:
NumberLong(9223372036854775807); // Truncates!
// Correct:
NumberLong("9223372036854775807"); // Exact!
Production Warning: Never pass unquoted large numbers into NumberDecimal() or NumberLong().

7. Architectural Trade-offs

Advantages
  • •Eliminates floating-point rounding discrepancies in financial computations
  • •Provides true 64-bit integers for high-scale distributed sequence IDs
  • •Native millisecond date ordering and timezone-neutral UTC storage
Disadvantages & Gotchas
  • •Decimal128 math operations in aggregation require more CPU cycles than hardware-accelerated 64-bit floats
  • •Requires explicit driver typing in weakly-typed languages like JavaScript

8. Technical Interview Questions

Q1: Why must financial monetary values in MongoDB always use Decimal128 instead of Double?

Standard BSON Doubles use IEEE 754 binary floating-point representation, which cannot accurately represent fractional decimal numbers like 0.1 or 0.7 without recurring binary approximation. Decimal128 uses base-10 decimal floating point with 34 digits of precision, guaranteeing exact mathematical results without rounding anomalies.

9. Staff-Level Ready Answer

"MongoDB supports Decimal128 (IEEE 754-2008), NumberLong (Int64), and UTC Date types. In financial applications, Decimal128 is mandatory to prevent binary floating-point rounding errors. Drivers must pass string values into Decimal128 constructors to avoid client-side float conversion before transmission."

10. Quick Knowledge Check

What is the correct way to instantiate a Decimal128 value in MongoDB to avoid precision loss?