Reputation: 61
I'm trying to fetch all records those have been created on today's date from mongodb using mongorepository or mongooperations or mongotemplate I want to match all records by Date only not on timestamps. Please refer my mongodb enteries below.
/* 1 */
{
"_id" : ObjectId("59135f13fc90f22b00c91df2"),
"_class" : "com.vistors.management.domains.EmployeeVisitor",
"checkedIn" : true,
"checkedInDate" : ISODate("2017-05-10T18:42:27.630Z"),
"visitor" : {
"$ref" : "VISITOR",
"$id" : ObjectId("59135f13fc90f22b00c91def")
},
"employee" : {
"$ref" : "EMPLOYEE",
"$id" : ObjectId("59135f13fc90f22b00c91df0")
}
}
/* 2 */
{
"_id" : ObjectId("59135f13fc90f22b00c91df3"),
"_class" : "com.vistors.management.domains.EmployeeVisitor",
"checkedIn" : true,
"checkedInDate" : ISODate("2017-05-10T18:42:27.638Z"),
"visitor" : {
"$ref" : "VISITOR",
"$id" : ObjectId("59135f13fc90f22b00c91dee")
},
"employee" : {
"$ref" : "EMPLOYEE",
"$id" : ObjectId("59135f13fc90f22b00c91df0")
}
}
/* 3 */
{
"_id" : ObjectId("5913ec9eafeb7a1e8df79d5f"),
"_class" : "com.vistors.management.domains.EmployeeVisitor",
"checkedIn" : true,
"checkedInDate" : ISODate("2017-05-11T04:46:22.425Z"),
"visitor" : {
"$ref" : "VISITOR",
"$id" : ObjectId("59135f13fc90f22b00c91dee")
},
"employee" : {
"$ref" : "EMPLOYEE",
"$id" : ObjectId("59135f13fc90f22b00c91df0")
}
}
I want to fetch all enteries from db those match with checkedInDate as today's date something like:
@Query("{'checkedInDate': {$gte: ?0, $lte:?0 }}")
List<EmployeeVisitor> findAllCheckedInToday(ZonedDateTime date)
or
@Override
public List<EmployeeVisitor> getTodayRecords() {
//Date date = Date.from(instant);
Query query = new Query().addCriteria(Criteria.where("checkedInDate").is(new Date()));
return mongoTemplate.find(query, EmployeeVisitor.class);
//Criteria.where("expenseDate").gte(calendar1.getTime()).lte(calendar2.getTime()).and("userid").is(uid);}
}
But I'm failed to achieve the required result, I'm not able to understand how can I query from db with date not date with timestamp.
Thanks for your help.
Jitender
Upvotes: 1
Views: 4985
Reputation: 412
you can change your repository method to something like this:
List<EmployeeVisitor> findByCheckedInDate(ZonedDateTime date)
Upvotes: 0
Reputation: 27068
Continuing from what @Veeram suggested. This is what you can do,
ZonedDateTime today = ZonedDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT, ZoneId.systemDefault());
ZonedDateTime tomorrow = today.plusDays(1);
repository.finByCheckedInDateBetween(Date.from(today.toInstant()), Date.from(tomorrow.toInstant()));
And you can change your repository method to something like this
finByCheckedInDateBetween(Date from, Date to)
Upvotes: 2