BSON

Also known as: Binary JSON

On this page 7

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.

ComponentSizePurpose
Document length4 bytes (int32)Total size, allowing a reader to skip the whole document
Type tag1 byteIdentifies the value type, such as 0x02 for string
Field nameVariable, null-terminatedKey of the element as a C string
ValueFixed or length-prefixedEncoded data according to the type tag
Terminator1 byte (0x00)Marks the end of the document
Byte layout of a BSON 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.

TypeEncodingWhy it matters
Double8-byte IEEE 754Default for floating-point numbers
Int32 and Int644 or 8 bytesExact integers beyond the safe range of JSON numbers
Decimal12816-byte IEEE 754-2008Exact decimal values for money and accounting
StringLength-prefixed UTF-8Text that may contain embedded null characters
ObjectId12 bytesCompact, roughly time-ordered unique identifier
UTC datetime8-byte signed millisecondsNative date type instead of a formatted string
BinaryLength, subtype and bytesRaw data such as hashes, UUIDs or small files
Timestamp8 bytesInternal ordering of replication operations
Common BSON types and their role

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.

FormatEncodingSchemaMain strength
BSONBinarySchemalessFast traversal and in-place updates
JSONTextSchemalessHuman readability and universal support
MessagePackBinarySchemalessCompactness for network transfer
CBORBinarySchemalessStandardized compactness for constrained devices
Protocol BuffersBinarySchema requiredSmall messages and strict contracts
BSON compared with related serialization formats

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.

SituationRecommended choiceReason
Storing documents in MongoDBBSON (automatic)Native format of the engine
Public web API responsesJSONUniversal client support
Compact messages between servicesMessagePack or Protocol BuffersSmaller payloads
Backup of a MongoDB collectionBSON dump filesPreserves every type exactly
Analytical storage of large tablesParquetColumnar compression and scans
Choosing BSON for a given task

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.