Home > database >  How to write criteria to check multiple conditions for mongoOperations in java
How to write criteria to check multiple conditions for mongoOperations in java

Time:10-17

Suppose collection is having 3 documents. For example:

{"document" : "001", "requestType" : "A", "valid" : "true"},

{"document" : "002", "requestType" : "A", "valid" : "false"},

{"document" : "003", "requestType" : "B"}

Each document has 2 attribute "requestType","document" mandatory. "valid" attribute is optional

What I want to achieve:

write criteria for a query that will check:

1-> what is the requestType of an document

if the requestType is "A" I need to check valid attribute is true.

else fetch the other "requestType" documents as well.

Final result in the response should be:

{"document" : "001", "requestType" : "A", "valid" : "true"},

{"document" : "003", "requestType" : "B"}

What I tried:

    Criteria criteria = new Criteria();
//others criteria are there as well thats why used orOperator
    criteria.orOperator(
                        Criteria.where("requestType").is("A"),
                        Criteria.where("valid").is(true)
                );
    final Query query = new Query();
    query.addCriteria(criteria);

It is providing response as: {"document" : "001", "requestType" : "A", "valid" : "true"},

But I needed {"document" : "003", "requestType" : "B"} in the response as well

CodePudding user response:

It looks like the query you are running needs a little update, currently the query makes {$or:[{ requestType:A}, {valid:true}]} but it should be: {$or:[$and:[{ requestType:A}, {valid:true}],"valid":{$ne:"A"}]}

  criteria.orOperator(
     Criteria.where("requestType").is("A").andOperator(Criteria.where("valid").is(true)),
      Criteria.where("requestType").ne("A")

  );
  • Related