0

I'm using the latest ReactiveMongo for play 2.7 and scala 2.12:

"org.reactivemongo" %% "play2-reactivemongo" % "0.17.1-play27"

and I want to create a find query and to count the number of documents returned from this query...

something like:

def countEntriesForReport(reportId: String) = {
    collection.find( Json.obj("reportId" -> reportId), Option.empty[BSONDocument]).count()
  }

But unfortunately there is no count here... how would you do that?

cchantep
  • 9,118
  • 3
  • 30
  • 41
jack miao
  • 1,398
  • 1
  • 16
  • 32
  • What's the return type? If it's some sort of collection like a List, you could just do a `.size` or `.length` or something on it – James Whiteley Jul 03 '19 at 12:52
  • In the past I've done stuff like `postsCollection.flatMap(_.find(Json.obj(), None)(JsObjectWriter, JsObjectWriter).cursor[Post]().collect[List](-1, Cursor.FailOnError[List[Post]]())).map(_.size)` (`postsCollection` is a `Future[BSONCollection]` and I'm looking for a List of documents which map to `Post` case classes in this example). This example is c&p from a Play 2.5.19 project I bodged together a while ago though so reactivemongo might've changed since then – James Whiteley Jul 03 '19 at 12:57
  • 1
    Rather `.count(query)` – cchantep Jul 03 '19 at 13:02

1 Answers1

-1

How about using a Cursor ?

I think this will be solve your issue:

  def countEntriesForReport(reportId: String): Future[List[User]] = {
    // the cursor of documents
    val found = collection.map(_.find(selector = Json.obj("reportId" -> reportId),
      projection = Option.empty[BSONDocument]).cursor[User]())

    // build (asynchronously) a list containing all of the users
    found.flatMap(_.collect[List](-1, Cursor.FailOnError[List[User]]()))
  }

// Now using the function
countEntriesForReport("85").map(list => println("Count: " + list.size))

This function will return the result of the query as a Future of List[User]. So we should use .map after function call to resolve the Future result and then get the size of it.

I was tested this code with ReactiveMongo version 0.16.2. Hopefully it will work with 0.17.1 as well.

Amoo Hesam
  • 461
  • 3
  • 13