This is my original tutorial, republished on this website. The examples are preserved. Tool versions and interfaces may have changed.
What is BSON? BSON Explained
What does BSON stand for?
BSON file types
BSON specifications and BSON types
| byte | 1 byte (8-bits) |
|---|---|
| int32 | 4 bytes (32-bit signed integer, two's complement) |
| int64 | 8 bytes (64-bit signed integer, two's complement) |
| uint64 | 8 bytes (64-bit unsigned integer) |
| double | 8 bytes (64-bit IEEE 754-2008 binary floating-point) |
| decimal128 | 16 bytes (128-bit IEEE 754-2008 decimal floating-point) |
How is BSON different from JSON?
| JSON | BSON | |
|---|---|---|
| Type | JSON files are written in text format. | BSON files are written in binary. |
| Speed | JSON is fast to read but slower to build. | BSON is slow to read but faster to build. |
| Space | JSON data is slightly smaller in byte size. | BSON data is slightly larger in byte size. |
| Encode and Decode | We can send JSON through APIs without encoding and decoding. | BSON files are encoded before storing and decoded before displaying. |
| Parse | JSON is a human-readable format that doesn't require parsing. | BSON needs to be parsed as they are machine generated and not human readable. |
| Data Types | JSON has a specific set of data types - string, boolean, number for numeric data types, array, object and null. | Unlike JSON, BSON offers additional data types such as bindata for binary data, decimal128 for numeric. |
| Usage | Used to send data through the network (mostly through APIs) | Databases use BSON to store data. |
Advantages of BSON. Why does MongoDB use BSON?
Lightweight and Traversable
Efficient
Additional Data Types
How to convert JSON to BSON (or vice versa)?
How to open a BSON document?
How to import and export BSON documents in MongoDB?
mongorestore -d db_name /path/file.bson
Here, db_name is the name of the database you want to import. path denotes the absolute path of your .bson file, while file represents the BSON file’s name.
For a single collection, run the following command on mongo shell.
mongorestore --drop -d db_name -c collection_name /path/file.bson
Here**, collection_name** defines the name of the collection that you want to import.
For restoring the complete folder exported by mongodump:
mongorestore -d db_name /path/
If you face any problems with a programming language, be sure to update the mongodb driver to the version that supports the language.
BSON Document Example. How BSON is stored in MongoDB Database?
{
"hello" : "world"
}
When storing the JSON document, it will be converted to the following.
\x16\x00\x00\x00 // total document size
\x02 // 0x02 = type String
hello\x00 // field name
\x06\x00\x00\x00world\x00 // field value (size of value, value, null terminator
\x00 // 0x00 = type EOO ('end of object')