$trim is a MongoDB aggregation expression that removes characters from both ends of a string. By default it strips whitespace. Pass chars to strip a custom character set instead—useful for cleaning imported names, emails, and padded codes.
Remember
$trim = trim() for aggregation
{ $trim: { input: <expression>, chars: <optional> } }
" Alice " → "Alice" // default: whitespace
"***VIP***" → "VIP" // chars: "*"
middle spaces stay // only ends change
null / missing → null
Left only → $ltrim
Right only → $rtrim
for each document:
s = evaluate(input)
if s is null or missing:
result = null
else:
set = chars or whitespace
while s starts with a char in set: remove it
while s ends with a char in set: remove it
result = s
emit { ..., field: result }
Reference
Cheat Sheet
Keep these facts handy while cleaning strings in a pipeline.
Topic
Detail
Type
Aggregation expression (not a find filter)
Syntax
{ $trim: { input: <expr>, chars: <opt> } }
Default
Trim Unicode whitespace both sides
Custom
chars: "*" strips * from both ends
Middle text
Unchanged (only ends are cleaned)
Null
null / missing → null
Siblings
$ltrim (left), $rtrim (right)
Try it
Live Preview
Watch $trim clean the ends of a string. Pick a sample and run the conversion.
Simulates $trim the same way as the mongosh examples below.
Result
input = " Alice Smith "
chars = (default whitespace)
$trim → "Alice Smith"
{ cleanName: "Alice Smith" }
Trace
Worked Walkthrough — Messy Name
One user document stores name: " Alice Smith " with spaces on both ends. Goal: a clean display name.
Calculation
Document:
{ _id: 1, name: " Alice Smith " }
$trim({ input: "$name" })
remove leading spaces → "Alice Smith "
remove trailing spaces → "Alice Smith"
Result:
cleanName: "Alice Smith"
(space between Alice and Smith stays)
Code
MongoDB Examples
We use a small users collection with padded names. First trim whitespace, then strip custom characters from a label. Run these in mongosh after inserting the sample data once.
Example 1 — Sample Data
Imagine three users imported with accidental spaces around names and emails. We save them in a collection named users.
mongosh
db.users.insertMany([
{ _id: 1, name: " Alice Smith ", email: " [email protected] ", badge: "***VIP***" },
{ _id: 2, name: " Bob Jones ", email: "[email protected] ", badge: "**Member**" },
{ _id: 3, name: " Carol Lee", email: " [email protected]", badge: "*Guest*" }
]);
How the Data Is Stored in MongoDB
After the insert, MongoDB keeps three documents in users. Run find() to see them:
mongosh
db.users.find()
Stored in MongoDB
[
{ _id: 1, name: " Alice Smith ", email: " [email protected] ", badge: "***VIP***" },
{ _id: 2, name: " Bob Jones ", email: "[email protected] ", badge: "**Member**" },
{ _id: 3, name: " Carol Lee", email: " [email protected]", badge: "*Guest*" }
]
Same stored documents. Still using the three users from Example 1.
Set the character set.chars: "*" means strip asterisks from both ends (not whitespace).
Stop at other letters. Trimming stops when it hits V, M, or G—so VIP, Member, and Guest remain.
Easy check.***VIP*** should become VIP.
Edge Cases & Pitfalls
Check these before using $trim in production pipelines.
middle
Middle characters stay
$trim never removes spaces or symbols between letters. Only the ends are cleaned.
chars
chars replaces whitespace mode
When you set chars, only those characters are stripped. Spaces are kept unless space is included in chars.
null
Null and missing become null
Missing fields return null, not an empty string. Guard with $ifNull if you need a default.
side
Need one side only?
Use $ltrim or $rtrim instead of trimming both ends.
Analysis
Performance Notes
Approach
Cost
Best for
$trim alone
Per-document string work
Cleaning display / match fields
$trim + case ops
Still O(docs)
Email / code normalization
Trim early
Cleaner later stages
Pipelines that $match or $group on text
Trimming is cheap compared with large sorts or joins. Clean strings before $match when padded values would otherwise miss equality checks.
Remember
Key Takeaways
Role: remove characters from both ends of a string.
Default: strips whitespace; optional chars for a custom set.
Middle text: never changed by $trim.
One side: use $ltrim or $rtrim.
One line:$trim answers “what is this string without junk on the ends?”—for cleaner matches, labels, and imports.
Frequently Asked Questions
$trim removes characters from both ends of a string. By default it strips Unicode whitespace. Pass chars to strip a custom set of characters instead.
Use { $trim: { input: <expression>, chars: <optional string> } }. input is required. If chars is omitted, MongoDB trims whitespace from both sides.
$trim cleans both ends. $ltrim removes from the start only. $rtrim removes from the end only. Use $trim for full cleanup on both sides.
No. Characters between the first and last non-trimmed character stay as they are. Only leading and trailing matches are removed.
$trim returns null when the input is null or the field is missing. It does not throw an error for null input.
Yes for the default whitespace case. Think of $trim as MongoDB’s aggregation version of trim()—run it in the pipeline, not as a standalone find() filter.