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

Spring Data MongoDB:如何避免使用$and操作符构建查询

避免Spring Data MongoDB生成$and操作符的方法

当然有更简洁的方式来生成你想要的查询格式!你不需要单独创建多个Criteria再用andOperator组合,直接在同一个Criteria对象上链式调用条件就能实现。

正确的写法:

Criteria criteria = Criteria.where("someField").is("someValue")
                           .and("otherField").is("otherValue");

这样生成的查询语句就是你期望的:

{ "someField": "someValue", "otherField": "otherValue" }

原理说明:

Spring Data MongoDB中,Criteria的.and()方法是用来在同一个查询文档中添加额外的字段条件,而不是生成$and操作符。只有当你需要组合逻辑上独立的条件组(比如混合$or和$and的复杂场景)时,才需要用到andOperator。对于简单的多字段相等匹配,链式调用.and()就足够满足需求啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:09:15