3

I need to skip a number of documents (offset) from a query, and only return limit number of documents that go after. I know the following naive approach:

collection.find(BSONDocument())
  .cursor[T].collect[List](offset+limit).map(_.drop(offset))

but it is not really desired because it will load offset+limit number of documents in JVM memory, whereas I'd like to filter them on the "database" side.

VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62

2 Answers2

6

Solution: use QueryOpts. Example:

collection.find(BSONDocument())
  .options(QueryOpts(skipN = offset))
  .cursor[T].collect[List](limit)

Note that using skip is not very efficient because mongodb does not support effective pagination, it will just skip the desired number by iterating through all the documents.

VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62
2

VasyaNovikov answer is certainly correct. Reactive mongo offers a more intuitive API:

collection.find(BSONDocument())
  .skip(offset)
  .cursor[T]
  .collect[List](limit, Cursor.FailOnError[List[T]]())
peterschrott
  • 570
  • 5
  • 25