BSON vs JSON
You type documents in mongosh using curly braces that look like JSON. But what lands on disk is not JSON text at all. Knowing the difference explains why new Date() behaves differently from the string "2024-01-01", and why numbers come in several kinds.
The rule
You write JSON-like text; MongoDB stores typed binary called BSON.
JSON (JavaScript Object Notation) is text. It has only six kinds of value: string, number, boolean, null, object, array.
BSON (Binary JSON) is how MongoDB encodes documents on disk and on the network. It keeps JSON's shape but adds:
- More types: Date, ObjectId, 32-bit and 64-bit integers, Double, Decimal128, binary data, regular expressions and others.
- Length prefixes: each document and element records its size, so the server can jump over fields without reading them character by character.
- Order kept: fields stay in the order you wrote them.
db.newArrivals.insertOne({
_id: 7,
title: "Kindred",
released: new Date("1979-06-01"), // a BSON Date, not text
stock: 4, // a BSON 32-bit integer
price: 6.75 // a BSON Double
})As JSON text, released could only be the string "1979-06-01". Strings compare letter by letter, so date maths and date ranges would be fragile. As a BSON Date it is a real moment in time.
| JSON | BSON | |
|---|---|---|
| Form | human-readable text | binary |
| Number types | one | Int32, Int64, Double, Decimal128 |
| Dates | none (use strings) | Date |
| Used by | APIs, config files | MongoDB storage and wire protocol |
When you export data or send it through an API, drivers convert BSON to Extended JSON, which spells special types out, for example { "$date": "1979-06-01T00:00:00Z" }, so nothing is lost.