MongoDB: What is BSON?

Introduction

In MongoDB, documents are stored in BSON. BSON stands for Binary JavaScript Object Notation. Like its name suggests, this is a binary-encoded serialization of JSON. Whenever you are making a query for a document in your database, what is returned is a BSON object. From then, a driver is responsible to decode the BSON object into a readable JSON object.

Why?

JSON is a format easy to read. Here is a example:

{
  "name": "Damien",
  "age": 25,
  "alive": true,
  "address": {
    "city": "Auzay",
    "country": "France"
  },
  "likes": ["apples", "football", 42]
}

JSON allows 6 different types:

  • String
  • Number
  • Null
  • Array
  • Objects
  • Boolean

We can express a lot of different things with this, but there are obviously some limitations. BSON provides a few more types:

  • Date
  • BinData ( Binary Data )
  • ObjectId
  • Regular Expression

And some others… See the complete list

How does it look like?

Let’s take a very simple document:

{"name: "Damien"}

A single key/value pair. In BSON, it would look something like this:

\x16\x00\x00\x00
\x02
\name\x00
\x06\x00\x00\x00Damien\x00
\x00

Let’s decompose this:

  • First line

Represents the total number of bytes represented by the document, here "name": "Damien" equals to 16 bytes.

  • Second line

Defines the type. \x02 means String.

  • Third line

Represents the field name, here name. The \x00 means null terminated.

  • Fourth line

Represents the length of the field value. Here 6 bytes. Damien is 5 bytes + 1 byte for the null terminated character. Then, represents the field value Damien.

  • Fifth line

End of object, indicates we’re done.

Conclusion

There you go, this was a very quick introduction to BSON. You don’t need to know this to be efficient with MongoDB. BSON is handled behind the scenes without you knowing it. If you wish to dig a bit deeper, you can check out the BSON spec.

Feel free to share and comment.
Have a nice day.

Your email address will not be published. Required fields are marked *

*