MongoDB uses BSON, a binary-encoded serialization for JSON documents. BSON extends on JSON data types offering for example, native date 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.
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 distinguish among them in querying using the $type operator.
For example, if we have a balance field in GBP with 32-bit integers and double data types, if the 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:
db.account.find( { "balance" : { $type : 16 } } );
db.account.find( { "balance" : { $type : "integer" } } );