MongoDB 聚合 - 如何替换条件中字符串内的变量

问题描述 投票:0回答:1

在有条件的字段中,如何替换句子中的值?我已经尝试过以下方法,但没有成功。

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

        
    }
},

我得到的结果:“Admin Credit of $credit.credit Credits”

预期结果:“10 学分的管理学分”

mongodb aggregation-framework aggregate
1个回答
1
投票

您应该使用

$concat
$toString
运算符进行字符串插值。

db.collection.aggregate([
  {
    $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"
            }
          }
        }
      }
    }
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.