Introduction to MongoDB $rtrim Operator
The MongoDB $rtrim
operator is used to remove specified characters from the end of a string. It can be combined with the $trim
operator to remove spaces and other specified characters from both ends of a string.
Syntax
The syntax for the $rtrim
operator is as follows:
{ $rtrim: { <field>: <character> } }
Here, <field>
is the field to be modified, and <character>
is the character to be removed from the end of the field.
Use cases
The $rtrim
operator is useful for scenarios where you need to remove specific characters from the end of a string. For example, it can be used to remove file extensions or query parameters from a URL.
Example
The following example demonstrates how to use the $rtrim
operator to remove specified characters from the end of a string.
Consider the following documents containing strings:
{ "_id": 1, "name": "John Smith##" }
{ "_id": 2, "name": "Mike Johnson###" }
{ "_id": 3, "name": "Sara Johnson#" }
The following example demonstrates how to use the $rtrim
operator to remove the ‘#’ character from the end of the strings:
db.collection.updateMany({}, [
{ $set: { name: { $rtrim: { input: "$name", chars: "#" } } } }
])
After executing the above example operation, the documents containing the strings will be updated as follows:
{ "_id": 1, "name": "John Smith" }
{ "_id": 2, "name": "Mike Johnson" }
{ "_id": 3, "name": "Sara Johnson" }
Conclusion
The $rtrim
operator is a very useful string manipulation operator that allows us to remove specified characters from the end of a string. It can be combined with the $trim
operator to remove spaces and other specified characters from both ends of a string. When cleaning strings in documents, the $rtrim
operator is a useful tool.