Java/MongoDB query by date

Viewed 81518

I stored a value as a java.util.Date() in my collection, but when I query to get values between two specific dates, I end up getting values outside of the range. Here's my code:

to insert

BasicDBObject object = new BasicDBObject();
...
object.put("dateAdded", new java.util.Date());
collection.insert(object);

to query

BasicDBObject query = new BasicDBObject();
query.put("dateAdded", new BasicDBObject("$gte", fromDate));
query.put("dateAdded", new BasicDBObject("$lte", toDate));
collection.find(query).sort(new BasicDBObject("dateAdded", -1));

when I query between Wed Jul 27 16:54:49 EST 2011 and Wed Jul 27 16:54:49 EST 2011 (basically fromDate = toDate), I get objects with dates like Tue Jul 26 09:43:37 EST 2011 which should definitely not be possible. What am I missing here?

7 Answers

You can do

    import org.bson.conversions.Bson;
    import static com.mongodb.client.model.Filters.*;
    import java.text.SimpleDateFormat;

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
    Bson filter = Filters.and(gte("date_field", format.parse("2018-10-01")),
                            lt("date_field", format.parse("2019-10-01")))

I approach the query like this

new Document("datetime",Document.parse(
    "{$gte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(fromDate) + "'), 
     $lte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(endDate) + "')}"
))

If you want the exact answers to do one more thing when you applying the date range use the UTC time for the same.

On your local machine, you can use the below code to find the UTC time from your machine or server:

java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("UTC"));
Related