Introduction
BSON is the binary form in which MongoDB stores and sends its documents. It holds the same structure as JSON, objects and arrays of values, and adds types JSON lacks, such as dates, 32-bit and 64-bit integers, decimals, raw binary and MongoDB’s 12-byte ObjectId.
Unlike most compact formats, BSON puts the length in front of every document and
string, so a reader can skip over values it does not need. That makes it fast to scan
but often larger than JSON. The mongodump tool writes each collection as
a .bson file.
Structure
All numbers are little-endian. A document is a 32-bit total length, then its elements, then a zero byte. Each element is a type byte, the field name as a zero-terminated string, and the value. Common types:
| Type | Value |
|---|---|
01 | 64-bit floating point number |
02 | string: a 32-bit length, UTF-8 bytes and a zero byte |
03 | embedded document |
04 | array, stored as a document with the keys 0, 1, 2… |
05 | binary data: a length, a subtype byte, then the bytes |
07 | ObjectId, 12 bytes |
08 | boolean, one byte |
09 | date and time: milliseconds since 1970 as a 64-bit integer |
0A | null |
10, 12 | 32-bit and 64-bit integers |
13 | 128-bit decimal |
A .bson file from mongodump is simply one document after
another, with no header.
Links
Software
- MongoDB Database Tools:
mongodump,mongorestoreandbsondump, which prints BSON as JSON (Windows, macOS, Linux) - MongoDB Compass (Windows, macOS, Linux)
Developers
Reference
- BSON specification, bsonspec.org