简体   繁体   English

Spring MongoDB - 使用多个 $or 条件编写查询

[英]Spring MongoDB - write a query with multiple $or conditions

For an assignment I have to write a query with multiple OR conditions.对于一项作业,我必须编写一个具有多个 OR 条件的查询。

If I had to write it using MongoDB Query Language it would be trivial如果我必须使用 MongoDB 查询语言来编写它,那将是微不足道的

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

I there a way to achieve this using Spring MongoDB?我有办法使用 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 [...]由于 com.mongodb.BasicDocument 的限制,您无法添加指定为 [...]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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