Search code examples
mongodbaggregation-frameworkaggregate

MongoDB Aggregate - How to replace variable inside a string in conditions


In a field with the conditions, how can I replace a value inside a sentence? I have tried the following but it didn't work.

{
    $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'
                  }
                }
              }
            }

        
    }
},

The result I got: "Admin Credit of $credit.credit Credits"

Expected result: "Admin Credit of 10 Credits"


Solution

  • You should work with $concat and $toString operators for the string interpolation.

    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