在有条件字段的Mongodb项目中,如何替换句子中的值?我已经尝试过以下方法,但没有成功。
{
$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
预期结果:
Admin Credit of 10 Credits
您应该使用
$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"
}
}
}
}
}
}
])