MongoDB查询异常:按lastAccessTimestamp排序过滤无效数据返回空
问题原因
你现在的代码里,两次调用addCriteria会把两个条件按AND逻辑组合,但一个文档不可能同时满足「lastAccessTimestamp小于等于指定日期」和「lastAccessTimestamp字段不存在」这两个互斥条件,自然返回空结果。另外你的需求还提到要处理字段为null的情况,这部分也得加入判断逻辑。
正确代码实现
根据你的需求,分两种场景处理:
场景1:需要查询包含过期、字段不存在、字段为null的实体
把这三个条件用OR逻辑组合起来,代码如下:
// 定义三个目标条件 Criteria expiredCond = Criteria.where("lastAccessTimestamp").lte(date); Criteria notExistsCond = Criteria.where("lastAccessTimestamp").exists(false); Criteria nullCond = Criteria.where("lastAccessTimestamp").is(null); // 用OR运算符组合三个条件 Criteria combinedCond = new Criteria().orOperator(expiredCond, notExistsCond, nullCond); Query query = new Query(); query.limit(3); // 按指定字段升序排序(注意需求里写的是lastUsedTimestamp,和代码里的lastAccessTimestamp是否是笔误?自行修正) query.with(Sort.by(Sort.Direction.ASC, "lastAccessTimestamp")); query.addCriteria(combinedCond);
场景2:需要查询排除过期、字段不存在、字段为null的实体(即只返回有效实体)
如果需求是移除这些无效实体,就用AND组合「字段存在、不为null、未过期」的条件:
Criteria validCond = new Criteria().andOperator( Criteria.where("lastAccessTimestamp").exists(true), Criteria.where("lastAccessTimestamp").ne(null), Criteria.where("lastAccessTimestamp").gt(date) ); Query query = new Query(); query.limit(3); query.with(Sort.by(Sort.Direction.ASC, "lastAccessTimestamp")); query.addCriteria(validCond);
核心要点
- 多次调用
addCriteria默认是AND逻辑叠加; - 用
orOperator可以实现多条件的OR组合; - 判断字段不存在用
exists(false),判断null值用is(null)。
内容的提问来源于stack exchange,提问作者J Harish
相关产品推荐
相关产品推荐

