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

MongoDB聚合:如何在条件判断的字符串中替换变量

解决MongoDB聚合$project阶段字符串变量替换问题

你当前的问题在于直接在字符串中写$credit.credit,MongoDB不会自动解析字符串里的变量引用,需要用聚合操作符来实现字符串拼接和变量插入。

可以使用$concat拼接字符串,结合$toString将数值类型的credit转换为字符串(因为$concat只能处理字符串类型),修改后的代码如下:

{
    $project: {
        "_id": 1,
        "credit": "$credit.credit",
        "fromAdmin": 1,
        "type": 1,
        "description": {
            "$cond": { 
                "if": { "$eq": [ "$fromAdmin", true ] }, 
                "then": {
                    "$concat": [
                        "Admin Credit of ",
                        { "$toString": "$credit.credit" },
                        " Credits"
                    ]
                },
                "else": {
                    "$cond": {
                        "if": { "$eq": ["$type","credit"]}, 
                        "then": {
                            "$concat": [
                                "Purchase of ",
                                { "$toString": "$credit.credit" },
                                " Credits"
                            ]
                        }, 
                        "else": "Subscription Payment"
                    }
                }
            }
        }
    }
}

关键说明:

  • $toString:将$credit.credit的数值转换为字符串,确保能和其他字符串片段拼接。
  • $concat:将多个字符串片段(固定文本+转换后的变量值)拼接成最终的描述字符串。

这样就能得到你期望的结果,比如当$credit.credit为10时,会生成"Admin Credit of 10 Credits"或"Purchase of 10 Credits"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:22:03