Home > OS >  Spring MongoDB - write a query with multiple $or conditions
Spring MongoDB - write a query with multiple $or conditions

Time:01-16

For an assignment I have to write a query with multiple OR conditions.

If I had to write it using MongoDB Query Language it would be trivial

{ $and : [ 
  { $or : [ { "field1" : "value1" }, { "field2" : "value2" } ] }, 
  { $or : [ { "field3" : "value3" }, { "field3" : null }, { "field3" : { $exists : true }} ] } 
] }

I there a way to achieve this using Spring MongoDB ?

I tried

Query query = new Query();
query.addCriteria(new Criteria().orOperator(
  Criteria.where("field1").is("value1"),
  Criteria.where("field2").is("value2"),
));
query.addCriteria(new Criteria().orOperator(
  Criteria.where("field3").is("value3"),
  Criteria.where("field3").is(null),
  Criteria.where("field3").exists(false),
));

and also tried

Query query = new Query();
query.addCriteria(
  Criteria.where("field3").is("value3")
  .orOperator(Criteria.where("field3").is(null))
  .orOperator(Criteria.where("field3").exists(false))
  .andOperator(
     Criteria.where("field1").is("value1")
     .orOperator(Criteria.where("field2").is("value2"))
);

I get the following message when trying to execute either queries.

Due to limitations of the com.mongodb.BasicDocument, you can't add a second '$or' expression specified as [...]

Any help would be greatly appreciated.

CodePudding user response:

You can try with this piece of code:

Criteria firstOrCriteria = new Criteria().orOperator(
    Criteria.where("field1").is("value1"),
    Criteria.where("field2").is("value2"));

Criteria secondOrCriteria = new Criteria().orOperator(
    Criteria.where("field3").is("value3"),
    Criteria.where("field3").is(null),
    Criteria.where("field3").exists(true));

Criteria andCriteria = new Criteria().andOperator(firstOrCriteria, secondOrCriteria);

Query query = new Query(andCriteria);
  • Related