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

MongoDB聚合查询:如何为超长摘要字段自动追加省略号

MongoDB聚合查询实现摘要截断与省略号追加

现有如下MongoDB聚合查询,用于获取_id为ObjectId("642617b84b1f458a6c895c64")的文档的title字段,以及summary字段的前50个字节内容:

db.posts.aggregate([
    {$match:{_id:ObjectId("642617b84b1f458a6c895c64")}},
    {$project:{_id:0, title:1, summary:{$substrBytes:["$summary", 0, 50]} }}
])

需求是:当summary字段的字节长度超过50时,在截取后的内容末尾追加“...”;长度不超过50时,直接返回原内容。

修改后的聚合查询

db.posts.aggregate([
    {$match: {_id: ObjectId("642617b84b1f458a6c895c64")}},
    {$project: {
        _id: 0,
        title: 1,
        summary: {
            $cond: {
                if: {$gt: [{$strLenBytes: "$summary"}, 50]},
                then: {$concat: [{$substrBytes: ["$summary", 0, 50]}, "..."]},
                else: "$summary"
            }
        }
    }}
])

逻辑说明

  1. 使用$strLenBytes计算summary字段的字节长度,和原查询的$substrBytes(按字节截取)逻辑保持一致;
  2. 通过$cond条件判断:如果字节长度大于50,就用$concat把截取的前50字节内容和“...”拼接;否则直接返回原summary;
  3. 如果你的场景需要按字符数(而非字节数)处理(比如包含中文等多字节字符),可以将$strLenBytes替换为$strLenCP,$substrBytes替换为$substrCP,确保按字符数判断和截取。

内容的提问来源于stack exchange,提问作者D. Rattansingh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:12:18