MongoDB : 从字符串中删除最后两个字符

MongoDB : Remove last two characters from String

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

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

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

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

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

MongoDB Playground