Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 70 ยท Documents and BSON

BSON Types

Learn the BSON types MongoDB stores: strings, numbers, dates, ObjectId, null versus missing, common type pitfalls and the $type operator, with runnable stand-ins.

JSON can describe a string, a number, a boolean, null, an array and an object. A database needs more: points in time, exact money amounts, 64-bit counters, binary data and unique identifiers. MongoDB therefore stores documents as BSON (Binary JSON), which has its own set of types. Each value in a document carries a type, and queries, sorting and indexes all depend on it.

This lesson walks through the types you meet in daily work, the bugs that happen when types are mixed by accident, and the difference between a field that is null and a field that is missing. The examples run on a small stand-in, because a real server is not available here; the shell commands are real and read-only.

The types you will use most

String UTF-8 text.
Numbers Int32, Int64 (long), Double, Decimal128.
Date A UTC instant in milliseconds.
ObjectId A 12-byte unique identifier.
1 / 2

The type table

Every BSON type has a name (used by the $type operator) and a number. These are the common ones:

Alias Number Typical use
double 1 Floating-point numbers such as 3.14
string 2 Text
object 3 Embedded document
array 4 List of values
binData 5 Binary data, UUIDs
objectId 7 Default _id
bool 8 true / false
date 9 Timestamps
null 10 Explicit null
regex 11 Stored regular expressions
int 16 32-bit integer
long 18 64-bit integer
decimal 19 128-bit decimal for exact values

(There are a few more, such as timestamp, which MongoDB uses internally for replication.)

Numbers

MongoDB has four numeric types. Int32 and Int64 (long) store whole numbers exactly. Double is a binary floating-point number, the same as JavaScript's Number, and it cannot represent many decimal fractions exactly (0.1 is stored as a nearby binary value). Decimal128 stores decimal numbers with up to 34 significant digits and is the type for money and anything else that must be exact.

Numbers of different types compare by value: an int 5, a long 5 and a double 5.0 are equal in queries and sorts. Which type a value gets when you insert it depends on the client. The Node.js and Python drivers store an integer that fits in 32 bits as int, a larger integer as long (Python) or double (Node, unless you use a Long object), and a float as double. In mongosh you can ask for a specific type:

JavaScript
db.stock.insertOne({
  sku: "A1",
  qty: Int32(12),                       // 32-bit integer
  views: Long("9007199254740993"),      // 64-bit integer, exact
  weight: 2.5,                          // double
  price: Decimal128("19.99")            // exact decimal
})

Strings, dates and ObjectId

Strings are UTF-8. Sorting compares them by bytes by default, so "B" comes before "a" and "10" comes before "9". If you need language-aware ordering, use a collation on the query or the collection.

A date is a number of milliseconds since 1970-01-01 UTC. Always store real dates, not strings like "03/04/2026" (is that March 4 or April 3?). An ISO string such as "2026-03-04" sorts correctly, but a real date supports date operators in aggregation (Expressions and Operators) and TTL indexes. In the shell, new Date() and ISODate("2026-03-04T10:00:00Z") create dates.

An ObjectId is the default _id type: 12 bytes holding a timestamp, a random value and a counter. _id and ObjectId takes it apart.

Binary, regular expressions and the rest

binData holds raw bytes, such as a hash or a UUID in its compact binary form. Keep large files out of documents (the limit is 16 MiB per document, see Documents, JSON and Field Types). A regex value can be stored, but regular expressions are mostly used inside queries (Text Matching and Regular Expressions).

Inspecting types with a stand-in

JavaScript only has one number, so the stand-in below uses tiny wrapper classes for Int32, Long and Decimal128, plus a bsonType function that names the type of any value. This mimics what the $type operator reports on a real server.

JS Naming the BSON type of each value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

On a real server you would ask the same question with a query such as db.products.find({ price: { $type: "decimal" } }), or the aggregation operator $type to compute the type of a field per document. Both are covered in Element and Evaluation Operators.

Null versus missing

A field can hold null, or it can be absent. They are different things, and queries treat them differently:

  • { field: null } matches documents where the field is null or missing.
  • { field: { $exists: false } } matches only documents where the field is missing.
  • { field: { $type: "null" } } matches only documents where the field is explicitly null.

This is a classic source of surprise: "find documents without a discount" returns the explicit nulls as well. Decide on one convention for "no value" (usually: leave the field out) and keep to it.

JS null versus missing in filters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Type pitfalls

Because MongoDB is flexible about types inside a field, bugs happen when two parts of an application disagree. Typical ones:

  • Numbers stored as strings. "10" sorts before "9", and { qty: { $gt: 5 } } does not match the string "10" at all, since a range query only compares values of the same type bracket. Convert before inserting.
  • Dates stored as strings. Date arithmetic, TTL indexes and date operators need real dates.
  • Floating-point money. Doubles cannot hold 0.10 exactly, so sums drift. Store money as integer cents or as Decimal128.
  • Large integers in JavaScript. JavaScript numbers are exact only up to 2^53 - 1. A 64-bit id read into a plain Number loses precision; use Long or BigInt.
  • Mixed types in one field. One document with age: "30" among numeric ones makes sorts and range queries behave oddly, and it is invisible until someone queries it. Schema Validation can reject it at write time.
JS Why types matter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which BSON type should you use for money amounts that must be exact?

    Doubles cannot represent many decimal fractions exactly. Decimal128 or whole cents avoid rounding drift.
  2. 2. Which filter matches only documents where the field exists and is explicitly null?

    { field: null } also matches missing fields, $exists: false matches only missing ones, and $exists: true also matches non-null values. $type: "null" is the exact test.
  3. 3. You store dates as strings like "03/04/2026". What is the main problem?

    Real date values support date arithmetic, sort correctly and enable TTL indexes. A string like 03/04/2026 sorts by characters and is ambiguous.
  4. 4. How do an int 5 and a double 5.0 compare in a query?

    Different numeric types compare by their numeric value, so 5 and 5.0 are equal in filters and sorts.

Summary

  • MongoDB stores BSON, which adds dates, ObjectId, binary data and several numeric types to JSON's basics.
  • Numeric types are int, long, double and decimal; they compare by value. Use Decimal128 or integer cents for exact money.
  • Strings sort by bytes by default; use collations for language-aware ordering.
  • Store real dates, not strings.
  • { f: null } matches null and missing; $exists: false matches missing only; $type: "null" matches explicit null only.
  • Mixed types inside one field cause silent query surprises. Validate types on write.
  • $type tests a value's BSON type by name or number.

Next, learn how documents are identified in _id and ObjectId.