简体   繁体   中英

find by today's date using spring data either @Query in mongorepository or Mongooperations or mongotemplate

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

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)

您可以将存储库方法更改为以下形式:

List<EmployeeVisitor> findByCheckedInDate(ZonedDateTime date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM