Spring Mongo存储库查找日期开始和日期结束都在当前日期时间之下的文档

时间:2018-12-26 05:36:54

标签: java mongodb mongodb-query spring-data-mongodb

我想在mongodb中以及使用Spring数据mongodb(特别是通过mongo存储库)查找所有文档。如果要在MySQL中使用,它将看起来像这样:

MySQL:

select * from car_reservations
where
    car_id = "abc123" and
    schedule_start <= now() and
    schedule_end >= now()

注意:有两个字段(schedule_start和schedule_end)是日期时间(joda)

问题:

1。在mongodb中这相当于什么?这是我最初的查询,仅使用car_id作为过滤器

db.car_reservations.find({"car_id":"abc123"}).pretty()

但是,我不确定如何表达schedule_startschedule_end的过滤器。

2。使用Spring Data MongoDB(MongoRepository)如何通过方法名称创建方法查询?如果不可能,如何使用查询注释进行查询?

public class CarReservation {
    @Id
    private String id;
    private String carId;
    private DateTime scheduleStart; //Joda Time
    private DateTime scheduleEnd; //Joda Time

    //Getters and Setters
}


public interface CarReservationDao extends MongoRepository<CarReservation, String> {

    List<CarReservation> findAllByCarId(String carId);

    // TODO: find all car reservations where car id is equal to something,
    // and schedule start is less than or equal to now()
    // and schedule end is greater than or equal to now()
    // [scheduleStart] <------ [now] ------> [scheduleEnd]

}

用于汽车预订的样本数据:

{
    "_id" : "01onqb9fuietqfqpqabrich92n_20181226T200000Z",
    "scheduleStart" : "2018-12-26T20:00:00",
    "scheduleEnd" : "2018-12-26T22:00:00",
    "carId" : "05a10e0e-eccb-426f-bd90-56eaa4f38271"
}

{
    "_id" : "01onqb9fuietqfqpqabrich92n_20181226T000000Z",
    "scheduleStart" : "2018-12-26T00:00:00",
    "scheduleEnd" : "2018-12-26T23:59:59",
    "carId" : "75a10e0e-ecfb-226d-bd96-36eaa4f38272"
}

谢谢!

0 个答案:

没有答案