0

The Find objects between two dates MongoDB is answering the mongoshell command. But I require it to do in Java. I have explained my question a bit more. hope this helps

Below is the object

 {
    "_id" : ObjectId("5a8f997fcdc2960adae4f91a"),
    "cobDate" : ISODate("2018-02-15T18:30:00.000Z"),
    "Version" : 1
}

Query that worked in MongoShell

db.getCollection('collection').find({"cobDate" : { "$gt" : ISODate("2018-04-04T00:00:00.000Z"), "$lte" : ISODate("2018-04-06T00:00:00.000Z")}})

Below is my Java code.

        String businessDate = "2018-04-05"; //This is the argument to be passed in string by user
        LocalDate sDate = LocalDate.parse(businessDate);
        LocalDate eDate = sDate.plusDays(1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date ssdate = format.parse(sDate.toString());
        Date eedate = format.parse(eDate.toString());

        String startDate = MongoConnect.toISO8601UTC(ssdate);
        String endDate = MongoConnect.toISO8601UTC(eedate);

        BasicDBObject query = new BasicDBObject();
        query.put("cobDate", BasicDBObjectBuilder.start("$gt", endDate).add("$lte", endDate).get()) ; 

        db.getCollection(collectionName).find(query)

here syso(query) output is-->

{"cobDate" : { "$gt" : "2018-04-04T00:00:00.000Z", "$lte" : "2018-04-06T00:00:00.000Z" } } 

and does not work for me where "cobDate" stored like ISODate("2018-04-05T00:00:00.000Z"

Amit Singh
  • 63
  • 2
  • 12
  • MongoDB BSON Dates "are **not** strings". In order to find a "single date" you actually look for the :"range" of possible dates between the start of the day you want and the start of the next day. – Neil Lunn Apr 19 '18 at 23:05
  • people are not reading question carefully. https://stackoverflow.com/questions/6840540/java-mongodb-query-by-date will work if date is stored as string like "2018-04-04T00:00:00.000Z" or "Wed Jul 27 16:54:49 EST 2011", but teh answer of this doesnot work for dates stored as ISODate("2018-04-05T00:00:00.000Z" – Amit Singh Apr 23 '18 at 06:37

1 Answers1

0

It's easier and faster to look for dates greater than or equal to your date and less than your date + 1 day than to try parsing text with a regex.

String sourceDate = "2018-02-15";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = format.parse(sourceDate);
Date endDate = DateUtil.addDays(myDate, 1);

collection.find(and(gte("Date", startDate ), lt("Date", endDate )));
ScottyD0nt
  • 348
  • 2
  • 8