mongodbscalareactivemongoplay-reactivemongo

Querying time field using ReactiveMongo and Play JSON


I am trying to the equivalent of this query using ReactiveMongo with Play Framework & JSON:

db.getCollection('people').find({'refreshed': {$gt: ISODate('2017-01-01')}})

I tried this:

def peopleFuture Future[JSONCollection] database.map(_.collection[JSONCollection]("people"))

And run the query:

val fromDate = LocalDate.parse("2017-01-01").atStartOfDay()
val query = Json.obj("$gte" -> fromDate)
peopleFuture.flatMap(people => listings.people(query).cursor[JsObject]().collect[List]())

This returns an empty sequence.

According to the documentation, a data/time field is represented as

JsObject with a $date JsNumber field with the timestamp (milliseconds) as value

However this doesn't seem to help much when querying.

I am using ReactiveMongo 0.12.1 with Play Framework 2.5


Solution

  • You can use JodaTime as follow:

    import org.joda.time.DateTime
    val fromDate = DateTime.parse("2017-01-01")
    val query = Json.obj("refreshed"->Json.obj("$gte" -> Json.obj("$date" -> JsNumber(fromDate.getMillis))))