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
相关产品推荐
相关产品推荐

