如何在MongoTemplate中打印聚合查询的执行计划
问题:MongoTemplate聚合管道如何实现MongoDB
explain('executionStats')的功能 我正在尝试使用MongoTemplate(spring-boot-starter-data-mongodb)编写聚合管道,代码如下:
Criteria ct = Criteria.where("category").in(List.of("Book","Electronics")); ProjectionOperation pj = Aggregation.project().and("name").as("productName") .and("price").as("productPrice") .andExpression("concat($category, '-', $name)").as("fk"); Aggregation agg = Aggregation.newAggregation(Aggregation.match(ct), pj); AggregationResults<Product> result = mongoTemplate.aggregate(agg, "items", Product.class);
我的目标是用Java代码复现以下MongoDB命令的功能,获取执行统计信息:
db.items.aggregate([ { $match: { category: { $in: ["Book", "Electronics"], }, }, }, { $project: { productName: "$name", productPrice: "$price", fk: { $concat: ["$category", "-", "$name"], }, }, }, ]).explain('executionStats');
解决方案
MongoTemplate的aggregate方法没有直接提供获取执行统计的入口,需要借助MongoDB Java驱动的底层API来实现。具体步骤如下:
- 获取目标集合的
MongoCollection对象 - 用驱动API构建对应的聚合管道(Bson格式)
- 调用聚合的
explain方法并指定EXECUTION_STATS级别
完整代码示例:
import org.bson.Document; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ExplainVerbosity; import java.util.Arrays; // 获取MongoCollection实例 MongoCollection<Document> collection = mongoTemplate.getCollection("items"); // 构建$match阶段 Bson matchStage = Filters.in("category", "Book", "Electronics"); // 构建$project阶段 Bson projectStage = Aggregates.project() .and("name").as("productName") .and("price").as("productPrice") .and(Arrays.asList("$category", "-", "$name")) .usingOperator("$concat") .as("fk"); // 组合聚合管道 List<Bson> pipeline = Arrays.asList(matchStage, projectStage); // 执行explain获取执行统计 Document executionStats = collection.aggregate(pipeline) .explain() .execute(ExplainVerbosity.EXECUTION_STATS); // 打印执行统计结果 System.out.println(executionStats.toJson());
补充说明
- 如果习惯用
Document手动构建管道,也可以这样写$project阶段:
Document projectDoc = new Document("$project", new Document() .append("productName", "$name") .append("productPrice", "$price") .append("fk", new Document("$concat", Arrays.asList("$category", "-", "$name"))));
- 执行结果
executionStats包含了查询的执行时间、扫描文档数、索引使用情况等详细统计信息,和MongoShell中explain('executionStats')的输出结构完全一致。
内容的提问来源于stack exchange,提问作者ananda
相关产品推荐
相关产品推荐

