Understanding BSON Data Types

1. Understanding Document Structure

ElementDetail
FormatBinary JSON (BSON), little-endian
Max document size16 MB
Max nesting depth100 levels
Field name limitNo size limit but must be UTF-8; cannot contain \0
OrderingField order preserved (unlike JSON objects in some langs)
_id fieldRequired, unique per collection, immutable
{
  "_id": ObjectId("65f0a1b2c3d4e5f6a7b8c9d0"),
  "name": "Alice",
  "email": "alice@example.com",
  "tags": ["admin", "ops"],
  "profile": { "age": 30, "city": "NYC" },
  "createdAt": ISODate("2026-01-15T10:00:00Z")
}

2. Working with String Type

AspectDetail
EncodingUTF-8
Max lengthBounded by 16MB doc limit
BSON type code2 ("string")
$type alias"string"
db.users.find({ name: { $type: "string" } });
db.users.find({ name: /^Ali/i });  // regex on strings

3. Working with Number Types

TypeBSON codeConstructorRange
Int3216NumberInt("42")±2.1×10⁹
Int64 (Long)18NumberLong("9000000000")±9.2×10¹⁸
Double13.14 (literal)IEEE 754 64-bit
Decimal12819NumberDecimal("9.99")34 decimal digits
Note: Use Decimal128 for monetary values to avoid floating-point rounding.

4. Working with Boolean Type

AspectDetail
Valuestrue, false
BSON code8
$type alias"bool"
Truthy in $exprNon-zero numbers, non-empty strings → true

5. Working with Date Type

AspectDetail
StorageInt64 ms since Unix epoch (UTC)
BSON code9
Constructorsnew Date(), ISODate("2026-01-15")
Range±290M years from epoch
Aggregation$dateToString, $year, $dateDiff
db.events.find({ createdAt: { $gte: ISODate("2026-01-01"), $lt: ISODate("2026-02-01") } });

6. Working with ObjectId Type

Byte RangeMeaning
0-3Unix timestamp (seconds, big-endian)
4-8Random per-process value
9-11Incrementing counter
const id = new ObjectId();
id.getTimestamp();   // Date object
ObjectId.createFromTime(1700000000); // for time-bounded queries

7. Working with Arrays

AspectDetail
BSON code4
StorageDocument with stringified numeric keys
Multikey indexingEach element gets an index entry
Equality matchMatches arrays containing the value or equal to the array
Operators$all, $elemMatch, $size, $in

8. Working with Embedded Documents

AspectDetail
BSON code3
Dot notation"profile.city"
Exact matchField order & value must match
Partial matchUse dot notation: { "profile.age": 30 }
db.users.find({ "profile.city": "NYC" });
db.users.updateOne({ _id: id }, { $set: { "profile.age": 31 } });

9. Working with Null and Undefined Values

TypeBSON codeNotes
Null10Use for "no value"
Undefined6 DEPRECATEDDo not use; not BSON 1.1
{x: null} query-Matches docs where x is null OR missing
{x: {$type: 10}}-Matches only explicit null
{x: {$exists: false}}-Matches only missing field

10. Working with Binary Data

SubtypeCodeUse
Generic0Arbitrary bytes
Function1Reserved
UUID4RFC 4122 UUID
MD55Hash storage
Encrypted6CSFLE / Queryable Encryption
User-defined128+Application use
db.files.insertOne({ _id: UUID(), payload: BinData(0, "SGVsbG8gV29ybGQ=") });

11. Understanding Regular Expression Type

FlagMeaning
iCase-insensitive
mMultiline (^ $ per line)
xExtended: ignore whitespace
s. matches newline
db.products.find({ name: /^iphone/i });
db.products.find({ name: { $regex: "iphone", $options: "i" } });
Note: Anchored prefix patterns (/^abc/) can use B-tree indexes; /abc/i usually cannot.

12. Understanding Timestamp Type

AspectDetail
BSON code17
Structure{t: seconds, i: ordinal} (8 bytes)
UseInternal oplog ordering; reserved for system use
ConstructorTimestamp(1700000000, 1)
vs DateDate for app data; Timestamp for replication/sharding