我的收藏夹中有一个文档,例如
{
"_id" : ObjectId("5e3aaa7cdadc161d9c3e8014"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2134",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:30:00Z")
}
{
"_id" : ObjectId("5e3aaacddadc161d9c3e8015"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2021",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:00:00Z")
}
我正在输入类似条件
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05";
String to = "2020-02-05";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.and("scheduledDepDateTime").gte(fromDate).lte(toDate);
但是我只获取具有时间00
的字段,而不同时获取两个文档。我有两份该日期的文件,但得到的只有一份。我尝试了很多事情,但没有成功。我只想比较日期而忽略时间。请帮助。
from和to日期必须分别是该日期的最低时间和最高时间;这将覆盖一天中的所有时间。
对于与$ and运算符使用相同的字段(“ scheduledDepDateTime”),必须使用Criteria
的andOperator
而不是and
(请参阅AND Queries With Multiple Expressions Specifying the Same Field)。
更新的代码:
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05 00:00:00";
String to = "2020-02-05 23:59:59";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.andOperator(where("scheduledDepDateTime").gte(fromDate), where("scheduledDepDateTime").lte(toDate)));
// Query qry = new Query(criteria);
// List<SomeClassName> result = mongoTemplate.find(qry, SomeClassName.class, "collection_name");
mongod中的ISODate存储为具有毫秒分辨率的纪元时间戳。
[dateFormat.parse
可能返回ISODate(“ 2020-02-05T00:00:00.000Z”),它将以1580860800000
的形式存储在数据库中。
这实际上意味着您的查询为{scheduledDepDateTime:{$gte: 1580860800000, $lte: 1580860800000}}
,因此满足过滤条件的唯一可能值是ISODate(“ 2020-02-05T00:00:00.000Z”)。
要获取该日期的所有文档,您可以尝试将toDate
设置为第二天,并使用$lt
代替$lte
。
如@prasad所建议todate必须是该日期的最短时间和最长时间这样,我必须将todate字段中的时间设置为23:23:59,这样才能起作用。
public static Date convertToDate(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}