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

MongoTemplate中使用多个orOperator报错,咨询正确多条件查询实现

解决Spring Data MongoDB多次调用orOperator引发的异常

先直接给你修正后的代码,解决这个异常问题:

方案1:如果你的逻辑是「createdAt <= 给定时间 或 updatedAt <= 给定时间 或 failureTime > 3」

public List<Notification> getNotificationByTime(long notificationTime) { 
    return mongoTemplate.find(
        new Query(
            Criteria.orOperator(
                Criteria.where("createdAt").lte(notificationTime),
                Criteria.where("updatedAt").lte(notificationTime),
                Criteria.where("failureTime").gt(3)
            )
        ), 
        Notification.class
    ); 
}

方案2:如果你的逻辑是「createdAt <= 给定时间,并且 (updatedAt <= 给定时间 或 failureTime >3)」

public List<Notification> getNotificationByTime(long notificationTime) { 
    return mongoTemplate.find(
        new Query(
            Criteria.where("createdAt").lte(notificationTime)
                .orOperator(
                    Criteria.where("updatedAt").lte(notificationTime),
                    Criteria.where("failureTime").gt(3)
                )
        ), 
        Notification.class
    ); 
}

为什么原代码会报错?

你遇到的异常信息已经点明了核心问题:

org.springframework.data.mongodb.InvalidMongoDbApiUsageException: 由于com.mongodb.BasicDocument的限制,无法添加第二个'$or'表达式'$or : [ { "failureTime" : { "$gt" : 3}}]',Criteria已包含'$or : [ { "updatedAt" : { "$lte" : 1549709060838}}]'.

MongoDB的查询文档是基于键值对结构的,同一个键不允许重复出现。你原代码里多次调用orOperator(),每次调用都会给Criteria对象新增一个$or键,这直接违反了MongoDB的文档结构规则,所以抛出了这个异常。

正确的用法是:所有需要用OR逻辑连接的条件,必须放在同一个orOperator调用中,这样Spring Data MongoDB才会把它们组装成一个$or条件数组,而不是生成多个重复的$or键。

内容的提问来源于stack exchange,提问作者Purushottam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:28:00