简体   繁体   中英

Spring MongoDB - write a query with multiple $or conditions

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM