0

In reactivemongo my query look like this:

val result =collName.find(BSONDocument("loc" -> BSONDocument("$near" ->
           BSONArray(51,-114)))).cursor[BSONDocument].enumerate()

result.apply(Iteratee.foreach { doc => println(+BSONDocument.pretty(doc))})

I want to print only top 2 result, so i pass the maxdocs value in enumerate and then query is

val result =collName.find(BSONDocument("loc" -> BSONDocument("$near" ->
         BSONArray(51,-114)))).cursor[BSONDocument].enumerate(2)

result.apply(Iteratee.foreach { doc => println(+BSONDocument.pretty(doc))})

But it's not workinng, it's print all document of query.

How to print only top 2 result ?

panky
  • 137
  • 1
  • 1
  • 10

1 Answers1

0

I basically stumbled over the same thing.

Turns out, that the ReactiveMongo driver transfers the result documents in batches, taking the maxDocs setting into account only when it wants to load the next batch of documents.

You can configure the batch size to be equal to the maxDocs limit or to a proper divisor thereof:

val result = collName.
  find(BSONDocument("loc" -> BSONDocument("$near" -> BSONArray(51,-114)))).
  options(QueryOpts(batchSizeN = 2)).
  cursor[BSONDocument].enumerate(2)

Or, alternatively, let MongoDB choose the batch size and limit the documents you process using an Enumeratee:

val result = collName.
  find(BSONDocument("loc" -> BSONDocument("$near" -> BSONArray(51,-114)))).
  cursor[BSONDocument].
  enumerate(2) &> Enumeratee.take(2)
cbley
  • 4,538
  • 1
  • 17
  • 32