在具有条件的字段中,如何替换句子中的值?我试过以下几种方法,但不起作用.

{
    $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 it.Credit Credit"

预期结果:"管理学分10学分"

推荐答案

您应该使用$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

Mongodb相关问答推荐

MongoDB 4.4如何使用未知密钥更新dict

通过mongoDB中的查找从管道中删除被阻止的用户

如何使用ID数组对一个集合中的金额求和并更新另一个集合中的字段?

MongoDB MQL,将列表一分为二,仅获取唯一值

lexik_jwt_authentication下无法识别的选项api_platform

在mongoose 中按键查找嵌套对象

MongoDB 支持的最 Big Data 库数

更新 Mongodb 中的多嵌套数组

Stripe:必须提供来源或客户

用 BsonRepresentation(BsonType.ObjectId) vs BsonId vs ObjectId 在 C# 中装饰属性之间的区别

如何在 mongodb 本机驱动程序中对 find() 进行字段 Select ?

MongoDB - 投影一个并不总是存在的字段

使用 MongoDB 进行嵌套分组

Spring Data MongoDB 中的独特之处

MongoDB如何判断是否存在

MongoDB MapReduce - 发出一个键/一个值不调用reduce

mongo中的稀疏索引和空值

Mongoid 不在查询中

带有条件的MongoDB聚合查找

无法从 mongodb 中删除集合