5

如何删除MongoDB中String的最后两个字符?

我尝试了以下解决方案,但没有奏效。

   $substr: [ "$document.field", 0, { $strLenCP: "$document.field" } - 2 ]
4

1 回答 1

8

您必须使用$add$subrtract来评估新字符串的长度:

db.collection.aggregate([
    {
        $project: {
            newStr: {
                $substr: [ "$document.field", 0, { $add: [ { $strLenCP: "$document.field" }, -2 ] } ]
            }
        }
    }
])

MongoDB游乐场

于 2019-06-11T05:37:05.620 回答