代码之家  ›  专栏  ›  技术社区  ›  Ajith

Mongodb聚合如何在条件下替换字符串中的变量

  •  0
  • Ajith  · 技术社区  · 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'
                      }
                    }
                  }
                }
    
            
        }
    },
    

    我得到的结果是:“管理员信用$Credit.Credit信用”

    预期成绩:“行政学分10学分”

    1 回复  |  直到 1 年前
        1
  •  2
  •   Yong Shun    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"
                }
              }
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground