The $trim operator removes leading and trailing characters from a string in MongoDB aggregation expressions. By default it strips whitespace from both sides; optionally you can specify which characters to remove.
01
Both Sides
Start and end trim.
02
Syntax
input + optional chars.
03
Whitespace
Default trim behavior.
04
Custom Chars
Strip symbols like *.
05
Use Cases
User input, imports.
06
Trim Family
$ltrim / $rtrim.
Fundamentals
Definition and Usage
In MongoDB’s aggregation framework, the $trim operator trims characters from both ends of a string. For example, " MongoDB " becomes "MongoDB" when you trim surrounding whitespace. This is one of the most common string-cleaning operations when working with user input, CSV imports, or legacy data that contains extra spaces.
Think of $trim as MongoDB’s pipeline version of JavaScript’s String.prototype.trim(), with an optional custom character set via the chars argument.
💡
Beginner Tip
$trim cleans both ends at once. If you only need to fix the start or end, use $ltrim or $rtrim instead for more precise control.
Foundation
📝 Syntax
The $trim operator takes an object with input and an optional chars field:
// Trim leading and trailing whitespace (default)
{ $trim: { input: "$name" } }
// Trim specific characters from both ends
{ $trim: {
input: "$code",
chars: "*#"
}}
// Trim a literal string
{ $trim: { input: " hello " } }
Syntax Rules
input — required; the string expression to trim (field reference or literal).
chars — optional; characters to remove from both ends. If omitted, whitespace is trimmed.
MongoDB removes matching characters repeatedly from the start and end until non-matching characters are found.
Characters in the middle of the string are never removed.
The chars argument defines which characters to strip from both ends. MongoDB removes them one by one from the start and end until it hits a character not in the set.
Example 3 — Trim and Lowercase Email
Combine $trim with $toLower to normalize email addresses:
Trimming removes accidental spaces; lowercasing ensures User@Mail.com and user@mail.com are treated the same. This prevents duplicate accounts caused by formatting differences.
Example 4 — Clean Both Name and Email in One Stage
Apply $trim to multiple fields in a single $addFields stage:
$addFields overwrites the existing fields with cleaned values. Use this when you want to normalize data in place before downstream stages like $match or $group.
Choose the right trim operator for your data. $trim is the go-to choice when both leading and trailing characters need cleanup.
Applications
🚀 Use Cases
User input cleanup — remove accidental spaces from names, emails, and form fields.
Import normalization — fix whitespace from CSV, spreadsheet, or legacy system imports.
Email standardization — pair with $toLower after trimming for consistent login keys.
Consistent matching — trim before comparisons so " active " matches "active".
Display formatting — prepare clean labels in $project for reports and APIs.
🧠 How $trim Works
1
MongoDB evaluates input
The input expression resolves to a string from a field or literal.
Input
2
Determines characters to strip
Uses chars if provided; otherwise defaults to Unicode whitespace.
Chars
3
Removes from both ends
Strips matching characters from the start and end until non-matching characters are found.
Trim
=
📝
Clean string
The expression returns the string with leading and trailing characters removed.
Wrap Up
Conclusion
The $trim operator is an essential string-cleaning tool for MongoDB aggregation pipelines. Use it to remove leading and trailing whitespace or custom characters from field values before display, matching, grouping, or further string operations.
Remember: input is required, chars is optional, and both ends are affected. For one-sided cleanup, use $ltrim or $rtrim. Next in the series: $trunc.
Use $trim when both leading and trailing characters need removal
Omit chars for standard whitespace cleanup
Pair with $toLower when normalizing emails and usernames
Clean strings in $addFields before matching or grouping
Use $ltrim or $rtrim when only one side needs fixing
❌ Don’t
Expect $trim to remove spaces in the middle of a string
Use $trim as a pipeline stage — it is an expression operator
Forget that null input returns null
Confuse chars with a prefix/suffix string — it is a character set
Trim numbers directly — convert with $toString first if needed
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $trim
Use these points when cleaning strings in MongoDB.
5
Core concepts
📝01
Both Ends
Start and end trim.
Purpose
🔢02
input Required
Field or literal.
Syntax
🛠03
chars Optional
Custom strip set.
Options
🔄04
Trim Family
ltrim / rtrim.
Compare
📑05
Data Cleaning
Users & imports.
Use case
❓ Frequently Asked Questions
$trim removes leading and trailing characters from a string. By default it strips whitespace from both sides. You can optionally pass a chars argument to remove specific characters instead.
The syntax is { $trim: { input: <expression>, chars: <optional string> } }. The input is required. If chars is omitted, MongoDB trims Unicode whitespace from both the start and end.
$trim removes characters from both sides of a string. $ltrim removes from the left (start) only. $rtrim removes from the right (end) only. Use $trim when you need full cleanup on both ends.
If the input expression is null, $trim returns null. It does not throw an error.
Use $trim inside expression stages such as $project, $addFields, and $set when cleaning user input, normalizing emails, preparing strings for matching, or fixing imported data.