0

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?

user3388925
  • 317
  • 2
  • 4
  • 9
  • `Document latestEntry = newColl.find().iterator().next();` This code is just returning the first document. You want to iterate over all documents. Ideally not *all* documents in the collection, but only those matching the timestamp (supply a filter to the `find` method). – Thilo Nov 06 '16 at 08:13
  • you should filter on timestamp in the query using $gt and $lt operators. It will be easier and way faster... see http://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb – felix Nov 06 '16 at 08:14

1 Answers1

0

The basic query is (using 3.x driver functions)

FindIterable<Document> findCursor
        = newColl.find(
            Filters.and(
                Filters.gte("timestamp_field", startTime),
                Filters.lte("timestamp_field", endTime)));

This will yield a collection of Document objects (and its up to you to map them to the expected result.)

mtj
  • 3,381
  • 19
  • 30