How do write a date range query in mongodb using reactive mongo in scala

3k views Asked by At

My session collection in database looks like

{ "_id" : ObjectId("545afeb0fb8af1531e70e762"), "sId" : "g38699im4g9fz6ri6pqd31odc0fzy6", "appId" : "c6s3ki1hgay9ntavyt8mxi54ukcfci", "events" : [ { "eType" : "untimed", "name" : "testing", "sId" : "g38699im4g9fz6ri6pqd31odc0fzy6", "st" : ISODate("2014-11-06T04:51:04Z"), "et" : ISODate("2014-11-06T04:52:44Z"), "screen" : "dummy", "data" : "{\"item\":\"immortals of meluha\",\"qty\":\"2\"}" }, { "eType" : "untimed", "name" : "testing", "sId" : "g38699im4g9fz6ri6pqd31odc0fzy6", "st" : ISODate("2014-11-06T04:51:04Z"), "et" : ISODate("2014-11-06T04:52:44Z"), "screen" : "dummy", "data" : "{\"item\":\"immortals of meluha\",\"qty\":\"2\"}" } ], "device" : { "model" : "", "mem" : "", "screen" : { "size" : "", "density" : "", "aspect" : "" } }, "network" : { "career" : "", "nType" : "" }, "location" : { "lat" : "", "long" : "" }, "user" : { "uId" : "ewkrmwyaidx5avo2adj7nh839mrzdc", "data" : "{}" }, "competetors" : [ ], "st" : ISODate("2014-11-06T04:51:04Z"), "duration" : -1, "tData" : [ ] }

I am trying to get the Sessions that lie between a date range. When I do something like

val query = BSONDocument("st" -> BSONDocument("$gt" -> BSONDateTime(1415229720*1000L) )  )
collection.find(query).cursor[BSONDocument].enumerate().apply(Iteratee.foreach { doc => println("found document: " + BSONDocument.pretty(doc)) })

It gives me all the sessions in the database while there are only 5 sessions greater than the given epoch.

I tried doing this too

val query = BSONDocument("st" -> BSONDocument("$gte" -> BSONDateTime(1415228760*1000L)).add( BSONDocument("$lte" -> BSONDateTime(1415229720*1000L) ) ) )

But it didn't work.

What is the correct way to query session class having "st" between two timestamps ?

2

There are 2 answers

0
Anshul Singhle On

The query looks like this:

 val query = BSONDocument( "st" -> BSONDocument("$gte" -> BSONDateTime(datetime1.getMillis),
                                                   "$lt" -> BSONDateTime(datetime2.getMillis))
                )

The reactive mongo BSONDocument() query format is almost exactly analogous to the mongo format as described here : http://cookbook.mongodb.org/patterns/date_range/ Specifically this snippet :

db.posts.find({"created_on": {"$gte": start, "$lt": end}})

A complete example: http://codepaste.net/8of6eb

0
toidiu On

So I think something like this should work:

val map = Map("$gt" -> min, "$lt" -> max)

val cursor = MongoObj.mongoPerform
  .find(
        Json.obj("date" -> map)
  )
  .cursor[Perform]