How do you query for all database entries within two timestamps in Java MongoDB 3.0?
Currently I am using this java method, but it doesnt do well in returning a set of documents within the start and end timestamp criteria. The code is a bit broken because it only returns the latest entry if it falls within the timestamp.
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;
}
What I want is to get a set of database entries within the two timestamps. How do you do this simply in Java MongoDB 3.0?