Skip to content

Instantly share code, notes, and snippets.

@ctcarrier
Created December 16, 2013 04:22
Show Gist options
  • Save ctcarrier/7982265 to your computer and use it in GitHub Desktop.
Save ctcarrier/7982265 to your computer and use it in GitHub Desktop.
Select a random document using
import reactivemongo.bson.BSONDocument
import reactivemongo.api.collections.default.BSONCollection
import reactivemongo.api.{QueryOpts, DB}
import reactivemongo.core.commands.Count
import reactivemongo.api.collections.default._
def getDocument(collection: BSONCollection): Future[Option[YourClass]] = {
val futureCount = db.command(Count(collection.name))
futureCount.flatMap { count =>
val skip = Random.nextInt(count)
collection.find(BSONDocument()).options(QueryOpts(skipN = skip)).one[YourClass]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment