Reactive Scala Driver for MongoDB

Asynchronous & Non-Blocking

Database and collections

Once you have a connection and resolved the database, the collections can be easily referenced.

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.MongoConnection
import reactivemongo.api.collections.bson.BSONCollection

def dbFromConnection(connection: MongoConnection): Future[BSONCollection] =
  connection.database("somedatabase").
    map(_.collection("somecollection"))

By default, it returns a BSONCollection, which implements the basic Collection trait.

The Collection trait itself is almost empty, and is not meant to be used as is. The collection operations are implemented by GenericCollection.

Go further:

If looking at the signature of the DB.collection function, it can be seen that it uses a CollectionProducer (resolved from the implicit scope. This producer is required to create the collection references.

By default the BSON producer is used, so there is nothing more to do.

It is this mechanism which makes ReactiveMongo can support other kinds of serialization, such as the JSON support.

Operations

The collection references provides the query and write operations: find, insert, update and remove

It also supports some administration commands: create, drop

It also includes a helper to manage indexes (see indexesManager).

Many of these methods take documents as a parameters. Indeed, they can take anything that can be represented as document, depending on the serialization pack (the BSON one by default).

Considering the default serialization (BSON), the functions requiring documents will accept any value for which is provided a BSONDocumentWriter.

The results from the operations can be turned into the appropriate types, if there is a BSONDocumentReader for this type in the implicit scope.

Additional Notes

When using the Play JSON serialization pack, it provides JSONCollection which is an implementation of GenericCollection that deals with Play JSON library, using its own de/serializations type classes (Reads[T] and Writes[T]).

Previous: Connect to the database / Next: Write documents