org.bson.Document多$or/$and表达式限制解析及MongoDB语法疑问
MongoDB多$or查询报错与疑问
报错信息:
org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the org.bson.Document, you can't add a second '$or' expression specified as '$or: [Document{{active=false}}, Document{{active=null}}]'; Criteria already contains '$or: [Document{{payerId=Document{{$in=[64aeae270d0313320626dc55]}}}}, Document{{payerLoginId=Document{{$in=[64aeae270d0313320626dc55]}}}}]'
问题解决方法
不要使用以下错误写法:
criteria.orOperator(Criteria.where(field).is(value), Criteria.where(field).is(anotherValue)); criteria.orOperator(Criteria.where(field2).is(value2), Criteria.where(field2).is(anotherValue2));
正确的写法是将多个$or嵌套在$and逻辑中:
criteria.andOperator( new Criteria().orOperator(Criteria.where(field).is(value), Criteria.where(field).is(anotherValue)), new Criteria().orOperator(Criteria.where(field2).is(value2), Criteria.where(field2).is(anotherValue2)));
疑问与补充
最初我以为问题是org.bson.Document的限制导致的,还误以为MongoDB支持这种查询语法:
{$or:[{field:"value"}, {field:"anotherValue"}], $or:[{field2:"value2"}, {field2:"anotherValue2"}]}
后来感谢aneroid指出,MongoDB查询语法本身就不允许存在多个$or。现在想向MongoDB团队提问:为什么多个等值条件会被隐式视为$and处理,但多个$or却不做类似的隐式处理?
内容的提问来源于stack exchange,提问作者radio
相关产品推荐
相关产品推荐

