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.
The shortcut
For any value, ask "Could plain JSON say exactly this?" If not, the value relies on a BSON type.
title: "Kindred"
A string. JSON can say this exactly.
The trap: storing dates as strings because the value "looks right". Sorting and range queries then work on text, not on time.
Drills
Answer fast — trust the rule.
In what format does MongoDB store documents on disk?
Which value type exists in BSON but not in JSON?
Why is released: "1979-06-01" weaker than released: new Date("1979-06-01")?
What does Extended JSON do?
BSON stores the length of each element. What does that buy the server?
Remember
- You write JSON-like text; MongoDB stores typed binary called BSON.
- Shortcut: ask "could plain JSON say exactly this?" If not, a BSON type is doing the work.
- Trap: dates stored as strings sort and compare as text, not as time.
