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 ]
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.
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> ] }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With