1

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.

1
  • 1
    I don't know spring very well, but I suspect you need to add an andOperator? Something like query.addCriteria(new Criteria().andOperator(new Criteria().orOperator(...), new Criteria().orOperator(...))) Commented Jan 13, 2023 at 17:04

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.