Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ]
like image 554
Dev Chauhan Avatar asked Jun 11 '19 05:06

Dev Chauhan


People also ask

What is trim MongoDB?

The character(s) to trim from input . The argument can be any valid expression that resolves to a string. The $trim operator breaks down the string into individual UTF code point to trim from input . If unspecified, $trim removes whitespace characters, including the null character.

What is $Substr in MongoDB?

Returns a substring of a string, starting at a specified index position and including the specified number of characters. The index is zero-based. $substr has the following syntax: { $substr: [ <string>, <start>, <length> ] }

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


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

like image 155
mickl Avatar answered Oct 02 '22 01:10

mickl