mongodbscalareactivemongoplay-reactivemongo

How to count documents with query in ReactiveMongo with Play's JSON library?


Let's consider I have a collection users that have the age attribute. Now I want to count either all documents in the collection users or only the ones which match the age attribute. So, I did the following:

  def count(age: Option[Int] = None) = {
    if (age.isEmpty) roles.count()
    else users.count(Json.obj("age" -> age))
  }

The problem is that users.count(Json.obj("age" -> age)) throws a compile error because the method count provided by reactive mongo expects the type Option[pack.Document]. Any idea how I can fix this?

I am using Reactive Mongo version 0.11.11 if that matters.


Solution

  • As said, it expects an Option of pack.Document, aka BSONDocument when pack is the BSON serialization one, or JsObject when using Play JSON.

    users.count(Some(Json.obj("age" -> age)))