Lesson 7 +10 XP

BSON Data Types

BSON Data Types

BSON (Binary JSON) is the binary format MongoDB uses to store documents. Because it's binary, it supports more data types than plain JSON.

Why BSON?

BSON allows fast encoding/decoding and supports extra types like dates, ObjectIds, and numbers of different sizes. Each BSON type has an integer number and a string alias.

Common BSON types

AliasWhat it is
doubleFloating-point number
stringText (UTF-8)
objectEmbedded document
arrayList of values
objectIdThe _id identifier
booltrue or false
dateMilliseconds since epoch
nullNo value
int32-bit integer
long64-bit integer
decimalDecimal128 for exact math
binDataBinary data

Dates

A BSON date is stored as a signed 64-bit integer counting milliseconds since January 1, 1970. You create one with:

new Date()
// or
ISODate("1990-01-01T00:00:00Z")

Why decimal matters

Binary floating-point can't represent some decimal values exactly - 0.1 * 0.2 gives 0.020000000000000004. For money or other exact math, use decimal128.

$type queries

You can find documents by the type of a field using the $type query operator with the alias:

db.posts.find({ likes: { $type: "int" } })

TL;DR

  • BSON = Binary JSON, MongoDB's storage format.
  • Supports extra types: date, ObjectId, int, long, decimal, binary.
  • Use $type to query by field type.