Reputation: 373
I need to execute a request in MongoDB which contains 4 logical "or" at once, I mean something like ((a == null || a == 0) || (b == null || b == 0))
I'm trying to execute this request but catch an exception Caused by: org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'null' criteria. Query already contains '{ "$or" : [{ "a" : null}, { "a" : 0.0}]}'
There is my code:
Criteria aCriteria = new Criteria();
aCriteria.orOperator(Criteria.where("a").is(null), Criteria.where("a").is(0.0d));
Criteria bCriteria = new Criteria();
bCriteria.orOperator(Criteria.where("b").is(null), Criteria.where("b").is(0.0d));
Query query = new Query();
query.addCriteria(aCriteria);
query.addCriteria(bCriteria);
List<POJO> arbitrages = mongoTemplate.find(query, POJO.class, "DB");
How to solve this problem?
Upvotes: 3
Views: 2749
Reputation: 383
I had really complex MongoDb query with lot of $or
, $and
and null
conditions. Because of large number of queried fields I was not in position to do something as @prasad proposed. Instead of it I was using different level for of nesting for each part of criteria. I used:
Criteria criteria = new Criteria();
criteria = new Criteria().andOperator(criteria, secondCriteria);
criteria = new Criteria().andOperator(criteria, thirdCriteria);
...
Upvotes: 0
Reputation: 14317
The following query Criteria
will work using the orOperator
:
Criteria c = new Criteria().orOperator(
Criteria.where("a").is(0),
Criteria.where("a").is(null),
Criteria.where("b").is(0),
Criteria.where("b").is(null)
);
Query query = new Query(c);
List<POJO> result = mongoTemplate.find(query, POJO.class, "DB");
Upvotes: 6