Search code examples
mongodbsubstringsubstr

MongoDB : Remove last two characters from String


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 ]

Solution

  • 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