如何在MongoRepository REST Api网址中同时使用排序和限制

时间:2019-07-23 09:13:01

标签: java mongodb spring-boot spring-data mongodb-rest

我无法使用spring bootsort之类的limit智能URL查询参数的功能。

我所拥有的MongoDb文档(数据)

{
        "_id" : ObjectId("5d300ee633ad616ea070bac5"),
        "_class" : "com.xyz.mongo.docs.IvrMongoLog",
        "jsonObject" : {
                "mode" : "ivr",
                "callee" : "128",
                "message" : [
                        {
                                "time" : "09:16:14",
                                "action" : "success full prompt is playing ",
                                "user_input" : "1",
                                "language" : "ar"
                        }
                ],
                "msisdn" : "218XXXXXX805",
                "timestamp" : "2019-07-18  09:16:14"
        }
}

mongoDb集合中有大约2000个或更多此类文档。

我需要的

当我在MongoRepository中使用SpringBoot应用程序时,我想创建一个API,该API可以根据timestamp字段以降序对我获取最后10个文档。

代码--API

@GetMapping(value="fetch/log/latest10",consumes=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CoreResponseHandler> fetchIvrCurrentDate(Pageable page){
        long l_time_start = System.currentTimeMillis();

        Page<IvrMongoLog> allPage = ivrMongoLogRepository.findLatest10(new PageRequest(0, 10));

        //new Sort(Sort.Direction.DESC,"jsonObject.timestamp")

        long l_time_end = System.currentTimeMillis();
        long l_diff = l_time_end-l_time_start;
        if(allPage!=null && allPage.getSize()>0) {
            return new  ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.OK, ResponseStatusEnum.SUCCESSFUL, ApplicationResponse.SUCCESSFUL,allPage,l_diff+" ms"),HttpStatus.OK);
        }
        if(allPage==null || allPage.getSize()==0) {
            return new  ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.NOT_FOUND, ResponseStatusEnum.FAILED, ApplicationResponse.Failed, "not found",l_diff+" ms"),HttpStatus.NOT_FOUND);            
        }
        return  new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed," > Bad request",l_diff+" ms"),HttpStatus.BAD_REQUEST);
    }   

代码-存储库

@Query("{}")
    Page<IvrMongoLog> findLatest10(Pageable pageable);

我正在尝试的POSTMAN网址

,但徒劳无功..是的,我能够将限制限制为10。但是没有发生排序。如何实现两种排序(最近的10条记录,最后一条记录在前)。

0 个答案:

没有答案