【问题标题】:find by today's date using spring data either @Query in mongorepository or Mongooperations or mongotemplate使用 mongorepository 中的 @Query 或 Mongooperations 或 mongotemplate 中的 spring 数据查找今天的日期
【发布时间】:2017-10-10 19:46:48
【问题描述】:

我正在尝试使用 mongorepository 或 mongooperations 或 mongotemplate 从 mongodb 获取在今天创建的所有记录我只想按日期而不是时间戳匹配所有记录。请参考下面我的 mongodb 输入。

/* 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")
}
}

我想从 db 中获取所有与 checkInDate 匹配的条目作为今天的日期:

@Query("{'checkedInDate': {$gte: ?0, $lte:?0 }}")
List<EmployeeVisitor> findAllCheckedInToday(ZonedDateTime date)

@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);}
}

但我未能达到所需的结果,我无法理解如何从带有日期而不是带有时间戳的日期的数据库中查询。

感谢您的帮助。

Jitender

【问题讨论】:

    标签: mongodb spring-data mongotemplate mongorepository


    【解决方案1】:

    您可以将存储库方法更改为以下内容:

    List<EmployeeVisitor> findByCheckedInDate(ZonedDateTime date)
    

    【讨论】:

      【解决方案2】:

      继续@Veeram 的建议。这是你可以做的,

      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()));  
      

      您可以将您的存储库方法更改为类似这样的方式

      finByCheckedInDateBetween(Date from, Date to)
      

      【讨论】:

      • 哦.. 是的,效果很好,感谢 pvpkiran 和 Veeram
      猜你喜欢
      • 1970-01-01
      • 2020-05-12
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 2021-04-16
      相关资源
      最近更新 更多