MongoDB uses BSON, a binary-encoded serialization for JSON documents. BSON extends the JSON data types, offering, for example, native data and binary data types.
BSON, compared to protocol buffers, allows for more flexible schemas that come at the cost of space efficiency. In general, BSON is space-efficient, easy to traverse, and time-efficient in encoding/decoding operations, as can be seen in the following table. (See the MongoDB documentation at https://docs.mongodb.com/manual/reference/bson-types/):
Type |
Number |
Alias |
Notes |
Double |
1 |
double |
|
String |
2 |
string |
|
Object |
3 |
object |
|
Array |
4 |
array |
|
Binary data |
5 |
binData |
|
ObjectID |
7 |
objectId |
|
Boolean |
8 |
bool |
|
Date |
9 |
date |
|
Null |
10 |
null |
|
Regular expression |
11 |
regex |
|
JavaScript |
13 |
javascript |
|
JavaScript (with scope) |
15 |
javascriptWithScope |
|
32-bit integer |
16 |
int |
|
Timestamp |
17 |
timestamp |
|
64-bit integer |
18 |
long |
|
Decimal128 |
19 |
decimal |
New in version 3.4 |
Min key |
-1 |
minKey |
|
Max key |
127 |
maxKey |
|
Undefined |
6 |
undefined |
Deprecated |
DBPointer |
12 |
dbPointer |
Deprecated |
Symbol |
14 |
symbol |
Deprecated |
In MongoDB, we can have documents with different value types for a given field and we distinguish among them when querying using the $type operator.
For example, if we have a balance field in GBP with 32-bit integers and double data types, if balance has pennies in it or not, we can easily query for all accounts that have a rounded balance with any of the following queries shown in the example:
db.account.find( { "balance" : { $type : 16 } } );
db.account.find( { "balance" : { $type : "integer" } } );
We will compare the different data types in the following section.