-
-
Notifications
You must be signed in to change notification settings - Fork 35
The basics
BSON is a Binary format for storing information. Although primarily used for MongoDB (connectors), it's also viable for communication between two parties.
BSON isn't smaller than JSON. It's actually bigger in some cases. But it's main advantage is that BSON is typesafe supporting the following data types.
- Double
- String
- Document
- Array
- ObjectId
- Bool
- DateTime
- 32-bit integer
- 64-bit integer
- Null value
- Binary
- Regular Expression
- Min Key
- Max Key
- Timestamp
- Javascript Code
- Javascript Code with Scope
Binary allows you to provide an UInt8 for the binary type. Which you can implement yourself to give meaning to the data.
BSON's primary type is a Document
. Documents are similar to Dictionaries but Documents can only use String
for their key, and BSON Values for their values.
Documents exist in another form too, an Array
. But here the key is a counter starting at 0
represented as a String. Therefore Documents can be instantiated to and from both Dictionary and Array. And like Dictionaries/Arrays, BSON Documents can contain other Documents.
In it's most basic form, this is how we create a Document.
import BSON
var document: Document = [:]
You'll probably notice that we explicitly declare the variable as a Document. We do this because BSON Documents are ExpressibleByDictionaryLiteral
and ExpressibleByArrayLiteral
which allows our initialiser ([:]
) to infer the type to a Document.
This means that we can also declare it like this:
import BSON
var document1: Document = []
var document2 = [] as Document
var document3 = [:] as Document