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, as the operations are implemented by GenericCollection.

Go further:

If looking at the signature of the DefaultDB.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.

This mechanism 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

ReactiveMongo provides 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 (e.g. for the BSON one, 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, a JSONCollection is provided as an implementation of GenericCollection that deals with Play JSON library, using its own de/serializations type classes (Play JSON Reads[T] and Writes[T]).

Previous: Connect to the database / Next: Write documents