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

如何在MongoDB中提取字符串最后字符并分组聚合求和?

解决方案

首先,替换$getMyLastCharInMyCode的核心是用MongoDB原生字符串操作符提取code字段的最后一个字符。这里有两种简洁可靠的实现方式,我会逐一说明:

方法1:用$strLenCP + $substrCP精准截取

这种方式先计算字符串长度,再定位到最后一个字符的位置截取,适合处理所有Unicode字符场景:

db.transactions.aggregate([
  // 提取code最后一个字符,同时兼容数据里的字段名笔误
  {
    $project: {
      last_index: {
        $substrCP: [
          "$code",
          { $subtract: [{ $strLenCP: "$code" }, 1] },
          1
        ]
      },
      total: { $ifNull: ["$total", "$totala"] } // 处理AAA5的totala字段,避免数据被忽略
    }
  },
  // 按最后一个字符分组计算总和
  {
    $group: {
      _id: "$last_index",
      total_sum: { $sum: "$total" }
    }
  }
])

步骤拆解:

  • $strLenCP: "$code":计算code的Unicode字符长度(比普通长度计算更适配多字节字符)
  • $subtract: [...]:用长度减1得到最后一个字符的起始索引
  • $substrCP: [...]:从起始索引处截取1个字符,也就是我们要的最后一位
  • $ifNull:针对你数据里AAA5的totala字段做兼容,如果total不存在就用totala的值

方法2:用$split + $arrayElemAt数组化提取

把字符串拆成单个字符的数组,直接取最后一个元素,写法更直观:

db.transactions.aggregate([
  {
    $project: {
      last_index: {
        $arrayElemAt: [ { $split: ["$code", ""] }, -1 ]
      },
      total: { $ifNull: ["$total", "$totala"] }
    }
  },
  {
    $group: {
      _id: "$last_index",
      total_sum: { $sum: "$total" }
    }
  }
])

步骤拆解:

  • $split: ["$code", ""]:把code按空字符串拆分,得到每个字符组成的数组
  • $arrayElemAt: [..., -1]:直接取数组的最后一个元素(-1表示倒数第一个位置)

最终结果

针对你提供的数据集,两种方法都会输出:

[
  { "_id": "1", "total_sum": 400 },
  { "_id": "2", "total_sum": 500 },
  { "_id": "3", "total_sum": 100 },
  { "_id": "5", "total_sum": 200 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:18:21