Reactive Scala Driver for MongoDB
Asynchronous & Non-Blocking
Overview of the ReactiveMongo BSON library
The BSON library of ReactiveMongo implements the BSON protocol, or Binary JSON, which is used by MongoDB to encode data. Because of that, when we use MongoDB we tend to manipulate a lot of BSON structures; thus the BSON library is designed with the following points in mind:
- ease of use
- strong typing
- efficiency
Documents and values
There is one Scala class for each BSON type, all in the reactivemongo.bson
package.
BSONDocument: set of key-value pairs
import reactivemongo.bson._
// BSONDocument(BSONElement*)
val doc1 = BSONDocument("foo" -> BSONString("bar"))
val doc2 = BSONDocument("lorem" -> 1)
Any type
T
for which aBSONWriter[T, _]
is available can be used as value for aBSONElement
in aBSONDocument
, as in thedoc2
of the previous example (see BSON typeclasses).
BSONArray: sequence of values
import reactivemongo.bson._
val arr1 = BSONArray(BSONString("foo"), BSONString("bar"))
val arr2 = BSONArray("lorem", "ipsum")
val arrField = BSONDocument("array_field" -> List("written", "values"))
As for
BSONDocument
, any type with aBSONWriter
(see provided handlers) can be added to aBSONArray
(seearr2
in the previous example). Moreover, aTraversable[T]
whose element typeT
has aBSONWriter[T, _]
can be used a BSON array (seearrField
in the previous example).
BSONBinary: binary data
BSONBoolean: boolean
BSONDBPointer: deprecated in the protocol
BSONDateTime: UTC Date Time
BSONDouble: 64-bit IEEE 754 floating point
BSONInteger: 32-bit integer
BSONJavaScript: JavaScript code
BSONJavaScriptWS: JavaScript scoped code
BSONLong: 64-bit integer
BSONMaxKey: max key
BSONMinKey: min key
BSONNull: null
BSONObjectID: 12 bytes default id type in MongoDB
BSONRegex: regular expression
BSONString: UTF-8 string
BSONSymbol: deprecated in the protocol
BSONTimestamp: special date type used in MongoDB internals
BSONUndefined: deprecated in the protocol
See how to handle the optional values.
All these classes extend BSONValue.
A document is represented by BSONDocument
. A BSONDocument
is basically an immutable list of key-value pairs. Since it is the most used BSON type, one of the main focuses of the ReactiveMongo BSON library is to make manipulations of BSONDocument as easy as possible.
import reactivemongo.bson._
val album = BSONDocument(
"title" -> BSONString("Everybody Knows this is Nowhere"),
"releaseYear" -> BSONInteger(1969))
val albumTitle = album.getAs[String]("title")
albumTitle match {
case Some(title) => println(s"The title of this album is $title")
case _ => println("this document does not contain a title (or title is not a BSONString)")
}
Furthermore, the whole library is articulated around the concept of BSONDocumentWriter
and BSONDocumentReader
.
These are type classes which purpose is to serialize/deserialize objects of arbitrary types into/from BSON. This makes usage of MongoDB much less verbose and more natural.