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

如何为MongoDB的Aggregation.match动态构建Criteria对象?

将JSON查询条件转换为Spring Data MongoDB的Criteria对象

解决方案:使用Criteria.fromDocument()方法

Spring Data MongoDB(2.0及以上版本)提供了直接将MongoDB查询文档转换为Criteria对象的工具方法,完全适配你提供的包含$and、$or的查询结构。

具体实现步骤

  1. 解析原始JSON,提取_filter字段对应的查询文档
  2. 调用Criteria.fromDocument()将查询文档转换为Criteria对象
  3. 直接用于Aggregation.match()

示例代码

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import java.util.List;

public class FilterConversionExample {
    public static void main(String[] args) {
        // 你的原始JSON字符串
        String originalJson = "{\"_filter\": {\"$and\": [{\"$or\": [{\"country\": \"India\"}, {\"age\": 20}]}]}, \"_page\": {\"pageNum\": 0, \"recordsPerPage\": 1}}";
        
        // 解析JSON并提取_filter部分
        Document rootDocument = Document.parse(originalJson);
        Document filterDocument = rootDocument.get("_filter", Document.class);
        
        // 转换为Criteria对象
        Criteria criteria = Criteria.fromDocument(filterDocument);
        
        // 用于聚合查询的match阶段,同时整合分页逻辑
        int pageNum = rootDocument.getEmbedded(List.of("_page", "pageNum"), Integer.class);
        int recordsPerPage = rootDocument.getEmbedded(List.of("_page", "recordsPerPage"), Integer.class);
        
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.skip((long) pageNum * recordsPerPage),
            Aggregation.limit(recordsPerPage)
        );
        
        // 后续可通过MongoTemplate执行聚合查询
        // mongoTemplate.aggregate(aggregation, "target-collection", YourResultDTO.class);
    }
}

注意事项

  • Criteria.fromDocument()会自动处理$and、$or、等值匹配等常见查询操作符,完全兼容你提供的JSON结构
  • 若使用Spring Data MongoDB 2.0以下版本,该方法不可用,需手动递归遍历查询文档,根据操作符构建Criteria对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:55:17