Reactive Scala Driver for MongoDB

Asynchronous & Non-Blocking

Find documents

Note: the following snippets of code use a BSONCollection (the default collection implementation return by db.collection()).

Performing a simple query

Queries are performed quite the same way as in the MongoDB Shell.

import scala.concurrent.Future

import reactivemongo.bson._
import reactivemongo.api.collections.bson.BSONCollection

def findOlder1(collection: BSONCollection): Future[Option[BSONDocument]] = {
  // { "age": { "$gt": 27 } }
  val query = BSONDocument("age" -> BSONDocument("$gt" -> 27))

  // MongoDB .findOne

Of course you can collect only a limited number of documents.


import reactivemongo.bson.BSONDocument
import reactivemongo.api.collections.bson.BSONCollection

def findOlder2(collection: BSONCollection) = {
  val query = BSONDocument("age" -> BSONDocument("$gt" -> 27))

  // only fetch the name field for the result documents
  val projection = BSONDocument("name" -> 1)

  collection.find(query, projection).cursor[BSONDocument]().
    collect[List](25) // get up to 25 documents

When using a serialization pack other than the BSON default one, then the appropriate document type must be used to define query (e.g. JsObject for the JSON serialization).

The find method returns a BSONQueryBuilder – the query is therefore not performed yet. It gives you the opportunity to add options to the query, like a sort order, projection, flags…


import reactivemongo.bson.BSONDocument

import reactivemongo.api.QueryOpts
import reactivemongo.api.collections.bson.BSONCollection

def findNOlder(collection: BSONCollection, limit: Int) = {
  val querybuilder =
    collection.find(BSONDocument("age" -> BSONDocument("$gt" -> 27)))

  // Sets options before executing the query

The class QueryOpts is used to prepared the query options.

When your query is ready to be sent to MongoDB, you may just call one of the following methods:

On a cursor, there are two interesting methods you can use to collect the results:

The collect method must be given a Scala collection type, like List or Vector. It accumulates all the results in memory, as opposed to enumerate.

Find and sort documents

The return type of the find method is a GenericQueryBuilder, which enables to customize the query, especially to add sort information. Like in the MongoDB console, you sort by giving a document containing the field names associated with an order (1 for ascending, -1 descending). Let’s sort our previous query by last name, in the alphabetical order (the sort document is also { lastName: 1 }).

import reactivemongo.bson.BSONDocument
import reactivemongo.api.collections.bson.BSONCollection

def findOlder3(collection: BSONCollection) = {
  val query = BSONDocument("age" -> BSONDocument("$gt" -> 27))

    // sort by lastName
    sort(BSONDocument("lastName" -> 1)).

Use Readers to deserialize documents automatically

As explained here, you can use the BSONDocumentReader / BSONDocumentWriter typeclasses to handle de/serialization between BSONDocument and your model classes.

import reactivemongo.bson._

case class Person(id: BSONObjectID, firstName: String, lastName: String, age: Int)

object Person {
  implicit object PersonReader extends BSONDocumentReader[Person] {
    def read(doc: BSONDocument): Person = {
      val id = doc.getAs[BSONObjectID]("_id").get
      val firstName = doc.getAs[String]("firstName").get
      val lastName = doc.getAs[String]("lastName").get
      val age = doc.getAs[Int]("age").get

      Person(id, firstName, lastName, age)

This system is fully supported in the Collection API, so you can get the results of your queries in the right type.

Any error raised by the read function will be caught by ReactiveMongo deserialization, and will result in an explicit Future failure.

import scala.concurrent.{ ExecutionContext, Future }

import reactivemongo.bson.{ BSONDocument, BSONDocumentReader }
import reactivemongo.api.collections.bson.BSONCollection

def findOlder4(collection: BSONCollection)(implicit ec: ExecutionContext, reader: BSONDocumentReader[Person]): Future[List[Person]] = {
  val query = BSONDocument("age" -> BSONDocument("$gt" -> 27))

  val peopleOlderThanTwentySeven = collection.find(query).
     * Indicate that the documents should be transformed into `Person`.
     * A `BSONDocumentReader[Person]` should be in the implicit scope.
    collect[List]() { people =>
    for (person <- people) println(s"found $person")


ReactiveMongo can directly return instances of a custom class, by defining a custom reader.

Next: Streaming

Suggest changes