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

如何使用MongoTemplate提取MongoDB字段子串并实现分组统计

解决MongoDB中提取branch字段中间值并统计出现次数的问题

嘿,刚好做过类似的需求,我来一步步教你怎么用MongoTemplate实现!

首先,我们的核心思路是利用MongoDB的聚合管道,先拆分branch字段提取出中间值,再分组统计数量。具体分这几个步骤:

1. 拆分branch字段并提取中间值

我们可以用$split操作符把branch按.分割成数组,比如India.Delhi.Saket会变成["India", "Delhi", "Saket"];接着用$arrayElemAt取数组的第1个索引元素(MongoDB数组是从0开始计数的),这样就能拿到我们需要的中间值了。

2. 分组统计出现次数

拿到中间值后,按这个值分组,用$count统计每组的记录数,最后还可以按需排序让结果更清晰。

具体代码实现

首先,我们需要定义一个接收结果的DTO类:

public class BranchCountResult {
    private String branch;
    private long count;

    // 构造函数、getter和setter
    public BranchCountResult(String branch, long count) {
        this.branch = branch;
        this.count = count;
    }

    // 省略getter和setter方法
}

然后用MongoTemplate构建聚合管道并执行:

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import org.springframework.data.domain.Sort;

// 注入MongoTemplate
private final MongoTemplate mongoTemplate;

public List<BranchCountResult> getBranchSubstringCount() {
    // 第一步:拆分branch字段并提取中间值
    AggregationOperation projectStage = project()
        .and("branch").split("\\.").as("branchArray") // 注意.是正则特殊字符,需要转义
        .and(arrayOf("branchArray", 1)).as("branchSubstring");

    // 第二步:按中间值分组统计数量
    AggregationOperation groupStage = group("branchSubstring")
        .count().as("count")
        .first("branchSubstring").as("branch"); // 把分组字段重命名为branch

    // 可选:按count降序排序
    AggregationOperation sortStage = sort(Sort.Direction.DESC, "count");

    // 组装聚合管道
    Aggregation aggregation = newAggregation(projectStage, groupStage, sortStage);

    // 执行聚合,指定集合名和结果类型
    return mongoTemplate.aggregate(aggregation, "Location", BranchCountResult.class).getMappedResults();
}

执行结果

运行这段代码后,你会得到类似这样的统计结果:

branchcount
Delhi2
Punjab1

关键点说明

  • 为什么用\\.?因为.在正则表达式里是匹配任意字符的特殊符号,所以拆分的时候需要转义成普通的点字符。
  • arrayOf("branchArray", 1)等价于MongoDB原生的$arrayElemAt: ["$branchArray", 1],用来取数组的第二个元素(索引1)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:57:32