[英]Find all mongo documents containing a field with a specific value using java
I am trying to use mongo's Java driver to read through a collection and only pull back documents with a field that is a range of values. 我正在尝试使用mongo的Java驱动程序来读取集合,并且仅回退具有一定范围值的字段的文档。 An example of this would be if I had data like
例如,如果我有类似的数据
{ "name" : "foo", "Color" : "white", "Date" : 20171116 }
{ "name" : "bar", "Color" : "black", "Date" : 20171115 }
{ "name" : "Jeff", "Color" : "purple", "Date" : 20171114 }
{ "name" : "John", "Color" : "blue", "Date" : 20171015 }
I would want to begin on 20171114 and end on 20171116 so I would do something like 我想从20171114开始到20171116结束,所以我会做类似的事情
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String begin = "20171114";
String end = "20171116";
Date startDate;
Date endDate;
Then I would need to convert the strings to a date and use a cursor like 然后,我需要将字符串转换为日期并使用类似
try {
startDate = df.parse(startDateString);
endDate = df.parse(endDateString);
BasicDBObject data = new BasicDBObject();
data.put("Date", new BasicDBObject( new BasicDBOject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
e.printStackTrace
}
However when I do this it returns nothing. 但是,当我这样做时,它什么也不会返回。
Answer: 回答:
I was trying to compare a number to a date which doesn't work so I converted my begin & end string to integers by doing 我试图将数字与无法正常工作的日期进行比较,因此我将开始和结束字符串转换为整数
Integer beginDate = Integer.valueOf(begin)
Integer endDate = Integer.valueOf(end)
and it worked. 而且有效。
I think you have saved values of Date
as numbers. 我认为您已将
Date
值保存为数字。 Please check your code once how you are saving and please let us know. 保存方式后,请检查您的代码,并告诉我们。
Considering that please try below by passing long values as 考虑到请尝试以下传递长值作为
try {
Long startDate = 20171114L;
Long endDate = 20171116L;
BasicDBObject data = new BasicDBObject();
data.put("Date", new BasicDBObject( new BasicDBObject( "$gte", startDate).append("$lte", endDate)));
} catch(ParseException e){
e.printStackTrace
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.