springmongodbspring-mongo

org.springframework.data.mongodb.InvalidMongoDbApiUsageException:you can't add a second 'user' criteria. Query already contains


when I am executing this code I am getting org.springframework.data.mongodb.InvalidMongoDbApiUsageException:Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'user' criteria. Query already contains '{ "user" : "5e269fad03f3c63845f5ca52" }'

    @Autowired
    MongoOperations mongoOperations;
     public List<UserTestDetails> getAllLatestTestByCompletedStatus(List<String> patientIds, String status,String typeOfTest){
            Query query=new Query();
            List<Query> queryList=new ArrayList<>();
            List<UserTestDetails> userTestDetailsList=new ArrayList<>();
         for(String patientId: patientIds) {

             if (!StringUtils.isEmpty(patientId)) {
                 query.addCriteria(Criteria.where("user").is(patientId));
             }
             if (!StringUtils.isEmpty(status)) {
                 query.addCriteria(Criteria.where("status").is(status));
             }
             if (!StringUtils.isEmpty(typeOfTest)) {
                 query.addCriteria(Criteria.where("typeOfTest").is(typeOfTest));
             }
             queryList= Arrays.asList(query);

         }
            userTestDetailsList = mongoOperations.find(query.with(new Sort(Sort.Direction.DESC, "lastUpdated")), UserTestDetails.class);


            return userTestDetailsList;
        }

As i am new to spring with mongo so I don't know where i am doing wrong


Solution

  • Query cannot have 2 same fields. Instead, use $in operator and no need to create extra Criteria. Use the following code:

    @Autowired
    private MongoOperations mongoOperations;
    
    public List<UserTestDetails> getAllLatestTestByCompletedStatus(List<String> patientIds, String status, String typeOfTest){
        Criteria criteria = new Criteria();
        if (!patientIds.isEmpty()) {
            criteria.and("user").in(patientIds);
        }
        if (StringUtils.isNotEmpty(status)) {
            criteria.and("status").is(status);
        }
        if (StringUtils.isNotEmpty(typeOfTest)) {
            criteria.and("typeOfTest").is(typeOfTest);
        }
    
        return mongoOperations.find(new Query(criteria).with(new Sort(Sort.Direction.DESC, "lastUpdated")), UserTestDetails.class);
    }