javamongodbmorphia

Morphia query date range


What is the equivalent of the following Mongo query in Morphia?

db.events.find({ "date": { $gte: ISODate("2001-01-01") , $lt: ISODate("2001-01-02")} })

Currently I have the following code

Query<Event> query = dataStore.find(Event.class);
query.field("date").greaterThanOrEq(startDate).field("date").lessThan(endDate);

but it results in the following Mongo query

{ "$and" : [ { "date" : { "$gte" : { "$date" : "2001-01-01T00:00:00.000Z"}}} , { "date" : { "$lt" : { "$date" : "2001-01-02T00:00:00.000Z"}}}]}

I suppose the end result is the same, but the resulting query is more verbose.


Solution

  • Use criteria with add method

    Something like

    Query<Event> query = datastore.find(Event.class);
    query.criteria("date").greaterThanOrEq(startDate).add(query.criteria("date").lessThan(endDate));