Spring Data MongoDB Date Between

ujava picture ujava · Apr 25, 2012 · Viewed 50.3k times · Source

I use spring data mongodb.

I want the records between two dates. The following MongoDB Query works:

db.posts.find({startDate: {$gte: start, $lt: end}});

My attempted Spring data query object code translation does not work:

Query query = new Query();
query.addCriteria(Criteria.where("startDate").gte(startDate)
                            .and("startDate").lt(endDate));

What is the correct order of method calls to build the Mongo query I need?

Answer

Yohan Liyanage picture Yohan Liyanage · Oct 29, 2012

Do not include the 'and("startDate")' part in your criteria.

Instead of :

query.addCriteria(Criteria.where("startDate").gte(startDate).and("startDate").lt(endDate));

You should use:

query.addCriteria(Criteria.where("startDate").gte(startDate).lt(endDate));

When you include the 'and("startDate")' part, Mongo see's it as two different entries on the same property.