Introduction to MongoDB $trim Operator
The MongoDB $trim
operator is a string aggregation operator used to remove specified characters or whitespace from a string. It is commonly used in scenarios where unwanted characters or whitespace need to be removed from a string and can be used in conjunction with other aggregation operators, such as $project
or $addFields
.
Syntax
The syntax of the $trim
operator is as follows:
{ $trim: { input: <string expression>, chars: <string expression> } }
Where input
is the string expression to be trimmed and chars
is the character expression to be removed from the string. If chars
is not specified, the default behavior is to remove whitespace characters from both ends of the string.
Use Cases
The $trim
operator is commonly used in scenarios where strings need to be formatted or processed. For example, you may need to remove unnecessary whitespace from a string for comparison purposes, or you may need to remove specific characters from a string for other purposes.
Examples
Here are two examples of using the $trim
operator.
Example 1
Suppose you have a collection users
that contains users’ names and email addresses. You want to find all users whose email addresses contain whitespace. You can use the following aggregation pipeline:
db.users.aggregate([
{ $project: { email: 1 } },
{ $match: { email: { $regex: /\s/ } } },
{ $addFields: { trimmedEmail: { $trim: { input: "$email" } } } }
])
This aggregation pipeline first uses the $project
operator to select the email address field. Next, the $match
operator is used to find all email addresses that contain whitespace characters. Finally, the $addFields
operator adds a new field trimmedEmail
to each matching document, which contains the email address with any whitespace characters removed.
Example 2
Suppose you have a collection products
that contains the names and prices of products. You want to find all products whose names contain a specific character and remove that character from the name. You can use the following aggregation pipeline:
db.products.aggregate([
{ $match: { name: { $regex: /A/ } } },
{ $addFields: { trimmedName: { $trim: { input: "$name", chars: "A" } } } }
])
This aggregation pipeline first uses the $match
operator to find all products whose names contain the character “A”. Next, the $addFields
operator adds a new field trimmedName
to each matching document, which contains the product name with all instances of the character “A” removed.
Conclusion
The $trim
operator is a very useful string aggregation operator that can help you easily format and process strings. It can be used in conjunction with other aggregation operators, such as $project
or $addFields
, to perform a variety of tasks based on your needs.