使用mongodb和spring数据mongodb进行日期查询

wtzytmuj  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(477)

我想搜索预订开始日期和预订结束日期在特定日期范围内的预订列表。
如果我在mysql中查询它,它会是这样的:
mysql数据库:

SELECT * FROM MotelReservations
WHERE motelId = 'ABC123' AND (
  (dateStart BETWEEN '2018-12-01 00:00:00' AND '2018-12-31 23:59:59') OR (dateEnd BETWEEN '2018-12-01 00:00:00' AND '2018-12-31 23:59:59')
)

但我不确定mongodb的查询等价于什么。
蒙哥达:

{
  "motelId": "ABC123",
  ???
}

另外,由于我将专门使用spring数据mongodb存储库方法。我想使用类似jpa的风格来查询它,在这里我可以使用 findAllBy... 方法名称。如果不可能,我可以用 @Query 注解。问题是,我不确定mongodb中的查询等价于什么。
spring数据mongodb(存储库):
MotelReservationDao 接口,按方法名称搜索 findAllBy... 或者使用查询注解 findAllByMotelIdAnd...(String motelId, ...) ```
@Query(???)
findAllReservationsThatFallsOnGivenDates

mongo文档示例:

{
"reservedBy": "Mang Kanor" ,
"id": "b1a7ddd3-ddfd-4624-8e85-79b47fb19f99" ,
"motelId": "ABC123" ,
"dateEnd": "2018-11-20T10:00:00" ,
"dateStart": "2018-11-20T09:00:00" ,
"summary": "Enjoy the moment in room 123"
}

j2qf4p5b

j2qf4p5b1#

mongodb中的等价查询

mongodb查询,可用于检索示例文档,

{$and: [
    {'motelId':{$eq:'ABC123'}},
    {$or: [
        {'dateStart':{$gte: '2018-11-01 00:00:00', $lte: '2018-12-31 23:59:59'}},
        {'dateEnd':{$gte: '2018-11-01 00:00:00', $lte: '2018-12-31 23:59:59'}}
    ]}
]}

或者含蓄地 $and 操作员:

{'motelId':{$eq:'ABC123'},
$or: [
    {'dateStart':{$gte: '2018-11-01 00:00:00', $lte: '2018-12-31 23:59:59'}},
    {'dateEnd':{$gte: '2018-11-01 00:00:00', $lte: '2018-12-31 23:59:59'}}
]}

spring数据mongo的等价查询

我不确定您是否可以使用spring数据方法签名创建这个complexe查询。但是你可以看这一节来了解更多的信息。

1. 使用@query注解

@Query("{'motelId':{$eq:?0},$or: [{'dateStart':{$gte:?1, $lte:?2}},{'dateEnd':{$gte: ?3, $lte:?4}}]}")
public List<MotelReservation> findReservationByDate(String motelId, Date from1, Date from2, Date to1, Date to2);

2. 使用mongotemplate

motelreservationdao接口

public interface MotelReservationDAO extends MongoRepository<MotelReservation, ObjectId>,
        CustomMotelReservationDAO {

}

custommotelreservationdao接口

public interface CustomMotelReservationDAO {
  public List<MotelReservation> findReservationByDate(String motelId, Date from1, Date from2, Date to1, Date to2); 
}

custommotelreservationdaoimpl类

public class CustomMotelReservationDAOImpl implements CustomMotelReservationDAO {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override    
    public List<MotelReservation> findReservationByDate(String motelId, Date from1, Date from2, Date to1, Date to2){

      Query query = new Query(
        Criteria.where("montelId").is(motelId)
        .andOperator(
          Criteria.where("dateStart").gte(from1).lte(from2),
          Criteria.where("dateEnd").gte(to1).lte(to2)
        )
      );

     return mongoTemplate.find(query, MotelReservation.class)
}

相关问题