Spring Data MongoDB Date Between

java, mongodb-java, spring, spring-data

Solution

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.

Problem

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?

Original source