In Mongo,
"org.mongodb.scala" %% "mongo-scala-driver" % "2.1.0",
I have this:
"_id" : ObjectId("5aeb1cc6f99d155c16478c96"),
"userId" : "2c48bc64-76cd-41b0-88af-b8dfea667960",
"eventAt" : ISODate("2018-05-03T14:29:25.964Z"),
"activity" : { "userAltId" : null,
...
"completedAt" : ISODate("2018-04-26T04:00:00Z"),
...
}
In my Mongo shell, when I run this query
> db.getCollection('wwactivities').find({ userId: "2c48bc64-76cd-41b0-88af-b8dfea667960" , "activity.completedAt": {$lte: ISODate("2018-04-26T23:59:59Z")}, "activity.completedAt": {$gte: ISODate("2018-04-26T00:00:00Z")}})
I get the correct resultset:
{ "_id" : ObjectId("5aeb1cc6f99d155c16478c96"), "userId" : "2c48bc64-76cd-41b0-88af-b8dfea667960", "eventAt" : ISODate("2018-05-03T14:29:25.964Z"), "activity" : {
"userAltId" : null, ...
"completedAt" : ISODate("2018-04-26T04:00:00Z"), ...
} }
In when I try to generate the query in scala code, and I use Scala-Mongo Filters like this:
val x = and( equal("userId", activityKey.userId), lt("activity.completedAt", atEndOfDay(toDate)), gt("activity.completedAt", atStartOfDay(fromDate)))
def atStartOfDay( date: Date ) = {
val cal = Calendar.getInstance()
cal.setTime(date)
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
cal.getTime()
}
Or explicitly like this:
val x = Document("activity.completedAt" -> Document("$gt" -> atStartOfDay(fromDate), "$lt" -> atEndOfDay(toDate)))
println( s"q: ${document.toJson()}")
In both cases, the println yields:
q: { "activity.completedAt" : { "$gt" : { "$date" : 1524715200000 }, "$lt" : { "$date" : 1524715200000 } } }
When I run
myCollection.find(x)
The result set is empty.
So in a nutshell, I write a query using ISODate in the Mongo shell and it works and returns the correct Document. However when I generate the query in Scala, it represents the date fields as int64 and the resultset is empty.
It looks like the generated document from the Filter represents the java.util.Date as a Long in the query.
scala> new Date(1524715200000L)
res74: java.util.Date = Thu Apr 26 00:00:00 EDT 2018
scala> new Date(1524801599999L)
res75: java.util.Date = Thu Apr 26 23:59:59 EDT 2018
Any ideas?