BSON, short for Binary JSON, is a binary-encoded serialization format for JSON-like documents that adds explicit type information and length prefixes to every element. Among data formats, it occupies a specific niche: it is designed less for human reading or compact transport and more for fast traversal and in-place manipulation inside a database engine, which is why it serves as the native storage and wire format of MongoDB.
In the wider field of data, BSON is best understood as an extension of the JSON data model rather than a replacement for it. It keeps the familiar structure of documents, arrays and key-value pairs, but introduces types that plain JSON lacks, such as dates, 64-bit integers, decimals and raw binary data.
How BSON encodes a document
A BSON document is a length-prefixed sequence of typed elements terminated by a null byte. The document begins with a 32-bit little-endian integer that states its total size in bytes, followed by the elements and a final 0x00 terminator.
Each element consists of three parts: a one-byte type tag, a null-terminated field name stored as a C string, and the encoded value. Because the type is stated explicitly, a parser never has to guess whether 42 is an integer or a floating-point number, which is a common source of ambiguity in textual JSON.
The following table shows how the components of a BSON document are laid out at the byte level.
| Component | Size | Purpose |
|---|---|---|
| Document length | 4 bytes (int32) | Total size, allowing a reader to skip the whole document |
| Type tag | 1 byte | Identifies the value type, such as 0x02 for string |
| Field name | Variable, null-terminated | Key of the element as a C string |
| Value | Fixed or length-prefixed | Encoded data according to the type tag |
| Terminator | 1 byte (0x00) | Marks the end of the document |
The length prefixes are the core design decision. Strings, embedded documents and binary values all carry their size, so a reader can jump over fields it does not need without parsing their contents. This property, called traversability, lets a database scan for one field inside a large record far faster than a JSON parser could.
BSON data types
BSON defines a richer type system than JSON, which only knows strings, numbers, booleans, null, objects and arrays. The extra types exist because a database must preserve exact values, sort them predictably and index them efficiently.
The table below lists the most frequently used BSON types and their practical significance.
| Type | Encoding | Why it matters |
|---|---|---|
| Double | 8-byte IEEE 754 | Default for floating-point numbers |
| Int32 and Int64 | 4 or 8 bytes | Exact integers beyond the safe range of JSON numbers |
| Decimal128 | 16-byte IEEE 754-2008 | Exact decimal values for money and accounting |
| String | Length-prefixed UTF-8 | Text that may contain embedded null characters |
| ObjectId | 12 bytes | Compact, roughly time-ordered unique identifier |
| UTC datetime | 8-byte signed milliseconds | Native date type instead of a formatted string |
| Binary | Length, subtype and bytes | Raw data such as hashes, UUIDs or small files |
| Timestamp | 8 bytes | Internal ordering of replication operations |
The ObjectId deserves particular attention. It combines a 4-byte creation timestamp, a 5-byte random value and a 3-byte counter, so identifiers generated on different machines rarely collide and sort approximately by insertion time. Several older types, such as undefined, DBPointer and symbol, are deprecated and should not appear in new data.
How BSON compares with JSON and other binary formats
BSON is not always smaller than JSON, which is the most widespread misconception about it. Field names are repeated in every document, integers occupy fixed widths and length prefixes add overhead, so a short JSON object can grow when converted to BSON.
The comparison below places BSON alongside neighboring formats in the same family of data formats.
| Format | Encoding | Schema | Main strength |
|---|---|---|---|
| BSON | Binary | Schemaless | Fast traversal and in-place updates |
| JSON | Text | Schemaless | Human readability and universal support |
| MessagePack | Binary | Schemaless | Compactness for network transfer |
| CBOR | Binary | Schemaless | Standardized compactness for constrained devices |
| Protocol Buffers | Binary | Schema required | Small messages and strict contracts |
MessagePack and CBOR use variable-length integers and omit document length headers, so they usually produce smaller payloads. BSON trades that compactness for predictable offsets, which matter when an engine updates a numeric field without rewriting the whole record. Schema-based formats such as Protocol Buffers are smaller still, because field names are replaced by numeric tags defined in advance.
Where BSON is used and how to work with it
BSON is used primarily as the storage and wire format of MongoDB, where every document, query and command travels in BSON. Official drivers for most programming languages convert native objects to BSON transparently, so application developers rarely handle the bytes directly.
For data exchange outside the database, MongoDB defines Extended JSON, a textual representation that preserves BSON types through wrapper keys such as $date or $numberLong. Tools such as mongodump write raw .bson files, while mongoexport produces Extended JSON or CSV for other systems.
The decision table below summarizes when BSON is a sensible choice.
| Situation | Recommended choice | Reason |
|---|---|---|
| Storing documents in MongoDB | BSON (automatic) | Native format of the engine |
| Public web API responses | JSON | Universal client support |
| Compact messages between services | MessagePack or Protocol Buffers | Smaller payloads |
| Backup of a MongoDB collection | BSON dump files | Preserves every type exactly |
| Analytical storage of large tables | Parquet | Columnar compression and scans |
Limitations and common mistakes with BSON
BSON imposes practical limits that shape schema design. In MongoDB, a single document may not exceed 16 megabytes, and nesting is limited to 100 levels, so large files belong in chunked storage such as GridFS rather than in one document.
- Losing types during conversion: exporting to plain JSON turns dates into strings and Int64 values into imprecise numbers.
- Long field names: because keys repeat in every document, verbose names noticeably inflate storage size.
- Using doubles for money: binary floating point cannot represent many decimal fractions, so Decimal128 is the safe choice for currency.
- Assuming field order is irrelevant: BSON preserves element order, and embedded documents with the same fields in a different order are not equal in matching.
Put simply
BSON is a way of storing structured information as computer-friendly bytes instead of readable text. It holds the same kind of content as JSON, with names and values grouped into records, but it also writes down the size and type of every piece.
Think of a filing cabinet in which every folder has its thickness printed on the tab. A clerk looking for one sheet can skip whole folders without opening them. That is what BSON gives a database: speed when finding and changing data, at the cost of files that people cannot read directly.
In practice
An online retailer stores its product catalog in MongoDB. Each product document contains a name, a price, a stock count, a list of tags and the date of the last update. The application sends ordinary objects to the driver, which encodes them into BSON before they reach the server.
Because prices are stored as Decimal128 rather than doubles, a total of 19.99 plus 0.01 remains exactly 20.00 in invoices. The last-update field is a native UTC datetime, so the team can index it and query all products changed in the past 24 hours without parsing strings.
During a nightly backup, mongodump writes the collection to BSON files. When the team restores it on a test server, every integer, decimal and date returns exactly as it was stored, which a plain JSON export would not have guaranteed.