mongodb fetching all documents in the range of two dates

FanonX :

I have a mongo database containing documents in the following structure

{
    _id:5e4f078e688bb974ed1dbc21
    timestamp:"Mon Mar 06 23:54:55 EST 2017"
    formatted_date:"2017-03-06 23:54:55"
    steps:13
    step_delta:13
}

I'm finding it tricky to get all documents (i believe there is a simple query for this, i'm just mistaken) that fall in between the specific dates needed.

this is my mongo db query

DBObject query = QueryBuilder.start().put("formatted_date").greaterThanEquals(startDate).and().put("formatted_date").lessThanEquals(endingDate).get();

Original, I was thinking it would be like the following sql query

String query = new StringBuilder("SELECT * FROM ").append(ACTIVITY_TABLE)
        .append(" WHERE formatted_date BETWEEN ").append(startDate)
        .append(" AND ").append(endDate).toString();

how do I make such a query in mongodb in java

ambianBeing :

You could create a range on the field formatted_date with this:

query = new BasicDBObject(
  "formatted_date",
  new BasicDBObject("$gte", startDate).append("$lte", endingDate)
);
cursor = collection.find(query);

try {
  while (cursor.hasNext()) {
    System.out.println(cursor.next());
  }
} finally {
  cursor.close();
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=419967&siteId=1