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

spring-data-mongodb如何在聚合match阶段应用自定义查询表达式

Spring Data MongoDB 3.1.1版本已支持该查询场景,以下是两种可行的实现方案:

方案1:使用原生Criteria API构造查询

针对动态属性的简单逻辑判断,可直接通过Criteria拼接查询条件,无需手动写$expr语句:

// 构造匹配逻辑:((attributes.name == 'Name1' && attributes.age > 40) OR (attributes.location == 'IN'))
Criteria nameAgeCondition = Criteria.where("attributes.name").is("Name1")
        .and("attributes.age").gt(40);
Criteria locationCondition = Criteria.where("attributes.location").is("IN");
Criteria finalCriteria = new Criteria().orOperator(nameAgeCondition, locationCondition);

// 统计匹配记录数
long matchCount = mongoTemplate.count(Query.query(finalCriteria), UserAttributesEntity.class);

如果确实需要使用$expr实现更复杂的字段运算逻辑,可使用以下写法:

Criteria exprCriteria = Criteria.expr()
        .and(ComparisonOperators.Gt.valueOf("attributes.age").greaterThanValue(40))
        .and(ComparisonOperators.Eq.valueOf("attributes.name").equalToValue("Name2"));

long matchCount = mongoTemplate.count(Query.query(exprCriteria), UserAttributesEntity.class);

方案2:直接封装原生MongoDB查询语句

如果查询逻辑动态生成、拼接Criteria成本较高,可直接将原生JSON查询语句封装为查询对象:

// 原生MongoDB $match 阶段JSON
String matchJson = "{ $expr: { $and: [ { $gt: [\"$attributes.age\", 40] }, { $eq: [\"$attributes.name\", \"Name2\"] } ] } }";
Query query = new BasicQuery(matchJson);

// 统计匹配记录数
long matchCount = mongoTemplate.count(query, UserAttributesEntity.class);

注意:attributes字段定义为Map<String, Object>时,Spring Data MongoDB会自动映射为BSON嵌套对象,直接使用attributes.xxx路径访问动态字段完全兼容,无需额外配置。

内容的提问来源于stack exchange,提问作者Siva Reddy Vippala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:18:04