Loading lessons...
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
| Alias | What it is |
|---|---|
| double | Floating-point number |
| string | Text (UTF-8) |
| object | Embedded document |
| array | List of values |
| objectId | The _id identifier |
| bool | true or false |
| date | Milliseconds since epoch |
| null | No value |
| int | 32-bit integer |
| long | 64-bit integer |
| decimal | Decimal128 for exact math |
| binData | Binary 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
$typeto query by field type.