MongoDB $trim Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $trim?

$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
UsePrefer
Clean both ends$trim
Clean start only$ltrim
Clean end only$rtrim

How to Use $trim in MongoDB

Pass the messy string, optionally set chars, then use the cleaned value downstream.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to the string field or expression to clean.
  3. Omit chars for whitespace, or set chars to the characters to strip from both ends.
  4. Optionally chain $toLower / $toUpper for full normalization.
PieceRequired?Role
inputYesString field, literal, or nested expression
charsNoCharacter set to strip; default = whitespace
$trimYesRemove matching characters from both ends

Pseudocode

Pseudocode
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 }

Cheat Sheet

Keep these facts handy while cleaning strings in a pipeline.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $trim: { input: <expr>, chars: <opt> } }
DefaultTrim Unicode whitespace both sides
Customchars: "*" strips * from both ends
Middle textUnchanged (only ends are cleaned)
Nullnull / missing → null
Siblings$ltrim (left), $rtrim (right)

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" }

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)

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()

Read each document like this:

Field in MongoDBExamplePlain English
_id1Document id (row number for this lesson)
name" Alice Smith "Name with extra spaces
email" [email protected] "Email with padding
badge"***VIP***"Label wrapped in * characters

How It Works

  1. Insert once. insertMany adds three user documents to users.
  2. Spaces are real characters. Leading/trailing spaces are stored as written until you trim them.
  3. find() shows the same shape. What you inserted is what you get back—ready for $trim next.

Example 2 — Trim Whitespace

Goal: add a cleanName field with spaces removed from both ends of name.

mongosh
db.users.aggregate([
  {
    $addFields: {
      cleanName: { $trim: { input: "$name" } }
    }
  }
]);

How It Works

  1. Read the stored name. Alice’s document has name: " Alice Smith " from Example 1.
  2. Trim both ends. With no chars, $trim removes leading and trailing whitespace.
  3. Keep the middle. The space between Alice and Smith stays; only the padding is removed.

Example 3 — Custom chars

Same users, but strip * characters from both ends of badge using the optional chars argument.

mongosh
db.users.aggregate([
  {
    $addFields: {
      cleanBadge: {
        $trim: {
          input: "$badge",
          chars: "*"
        }
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the three users from Example 1.
  2. Set the character set. chars: "*" means strip asterisks from both ends (not whitespace).
  3. Stop at other letters. Trimming stops when it hits V, M, or G—so VIP, Member, and Guest remain.
  4. 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.

Performance Notes

ApproachCostBest for
$trim alonePer-document string workCleaning display / match fields
$trim + case opsStill O(docs)Email / code normalization
Trim earlyCleaner later stagesPipelines 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.

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.

Next: $trunc

Truncate a number toward zero in an aggregation pipeline.

$trunc tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful