You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:55:06