0
如何查询Java MongoDB 3.0中两个时间戳内的所有数据库条目?Java MongoDB 3.0+时间戳查询
目前,我正在使用这种java方法,但它在开始和结束时间戳条件中返回一组文档方面做得并不好。该代码有点破,因为它只在时间戳内返回最新条目。
public static Reading getReadingsBetween(String type,Timestamp startTime,Timestamp endTime) {
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("SampleDB");
MongoCollection<Document> newColl;
Gson gson = new Gson();
newColl = db.getCollection("SampleCollection");
Document latestEntry = newColl.find().iterator().next();
String json = latestEntry.toJson();
Reading reading = gson.fromJson(json, Reading.class);
String thisTimestamp = reading.getGw_timestamp();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsedTimestamp = null;
try {
parsedTimestamp = df.parse(thisTimestamp);
} catch (ParseException e) {
return null;
}
Timestamp gwTimestamp = new Timestamp(parsedTimestamp.getTime());
mongo.close();
if (gwTimestamp.after(startTime) && gwTimestamp.before(endTime)) {
return reading;
}
return null;
}
我想要的是在两个时间戳内获取一组数据库条目。你如何简单地在Java MongoDB 3.0中做到这一点?
' document latestEntry = newColl.find()。iterator()。next();'这段代码刚刚返回第一个文档。您想遍历所有文档。理想情况下,不是集合中的所有*文档,但只有那些匹配时间戳的文档(为'find'方法提供过滤器)。 – Thilo
您应该使用$ gt和$ lt操作符在查询中的时间戳上过滤。它会更容易,更快捷...请参阅http://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb – felix