Retrieving the documents from the collection of Mongo db based on today's date

1.1k views Asked by At

I am newbie to mongodb, I have some issues while querying the database to retrieve the documents based on the current date. While saving the document to database, I am setting the billingDate field by using

SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = sdf.parse(billingDate);

So the Date field of my database is:

"billingDate" : ISODate("2017-01-02T00:00:00Z")

I tried to query as follows:

Query query=new Query();
query.addCriteria(Criteria.where("billingDate").lte(new java.util.Date()));

By executing the above query, I am getting the previous bills as well but I need only for today(I don't want to consider the timestamp in it). Please help me to get the bills of current date only. Any suggestions would be appreciable.

2

There are 2 answers

5
s7vr On BEST ANSWER

You can try something like this. This will get you the current date with time set to midnight in UTC.

LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
1
Chirdeep Tomar On

Your criteria is wrong, you are using lte which means less than equal. Use eq

http://api.mongodb.com/java/3.0/?com/mongodb/client/model/Filters.html