Spring 数据MongoDB: 查询月份

Spring Data MongoDB: query for month

我正在使用 Spring-boot 开发一个 webApp,我想创建一个查询 findByMonth(int or String month) 但我希望能够使用例如 findByNameAndMonth(String name , month) 或 findByIdAndMonth() 可能吗? 日期有 LocalDate 类型。

我有一个这样的对象:

public final class Alarm {
  @id
  private final String id;
  private final String type;
  // ....
  private final LocalDate date; 

它是一个 mongoRepository:

 public interface AlarmRepository extends MongoRepository<Alarm, String>{
 }

查询应该给出与此查询相同的结果,例如:

db.alarm.find({ $where : 'return this.date.getMonth() == 5'})

是的,这是可能的。 Spring 数据需要在存储库方法名称中使用相同的变量名称。例如: public final class Alarm { @id private final String id; private final String type; .... private final LocalDate date;

然后在您的存储库中,方法名称应如下所示。

findByIdAndDate(String id, LocalDate date); findByIdAndType(String id, String type);

LocalDate 作为 ISODate 存储在 MongoDB 中,因此无法直接访问它的属性(date.month 只是不起作用,方法 getMonth() 必须被使用)。

这导致使用 Spring 数据中的日期有点棘手。为了解决您的问题,我建议在您的存储库中创建此方法:

List<Alarm> findByDateBetween(LocalDate from, LocalDate to);

但是你必须注意边界条件(月初和月末)。

另一种选择是将日期存储为普通对象并通过其属性访问月份,如 documentation 中所述。