MongoDB : Remove last two characters from String

Viewed 2801

How to remove the last two characters of String in MongoDB?

I have tried below solution but it did not work.

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

You have to use $add or $subrtract to evaluate the length of a new string:

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

MongoDB Playground

Related