Find objects between two dates MongoDB正在回答mongoshell命令。但我要求它用Java做。我已经解释了我的问题了。希望这有帮助
以下是对象
{
"_id" : ObjectId("5a8f997fcdc2960adae4f91a"),
"cobDate" : ISODate("2018-02-15T18:30:00.000Z"),
"Version" : 1
}
在MongoShell中使用的查询
db.getCollection('collection').find({"cobDate" : { "$gt" : ISODate("2018-04-04T00:00:00.000Z"), "$lte" : ISODate("2018-04-06T00:00:00.000Z")}})
以下是我的Java代码。
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)
这里syso(查询)输出是 - >
{"cobDate" : { "$gt" : "2018-04-04T00:00:00.000Z", "$lte" : "2018-04-06T00:00:00.000Z" } }
并不适合我在哪里" cobDate"存储如 ISODate(" 2018-04-05T00:00:00.000Z"
答案 0 :(得分:0)
查找大于或等于您的日期且小于您的日期+ 1天的日期比尝试使用正则表达式解析文本更容易,更快。
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 )));