Java/MongoDB query by date
What you're doing is querying only with {$lte: toDate}
losing $gte
operator in the key overwrite. What you want is:
query.put("dateAdded", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
If you are using MongoTemplate of Spring-Data Mongodb, you can do the same in following way:-
public List<Link> getLinksBetweenDate(Date startDate, Date endDate) {
Query query = new Query().addCriteria(Criteria.where("updatedOn").gt(startDate).lte(endDate));
return mongoTemplate.find(query, Link.class);
}
Using mongo client 3.0
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
Bson filter = new Document("$gte", format.parse("2015-05-01T00:00:00Z")).append("$lt", format.parse("2015-05-02T00:00:00Z"));
long count = db.getCollection("colection").count(new Document("field",filter) );