MongoDB $trim Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Operations

What You’ll Learn

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.

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.

📝 Syntax

The $trim operator takes an object with input and an optional chars field:

mongosh
{
  $trim: {
    input: <expression>,
    chars: <optional string>
  }
}

Common Patterns

mongosh
// 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.
  • If input is null, the result is null.
  • Use inside $project, $addFields, or $set.

💡 $trim vs $ltrim vs $rtrim

" hello " + $ltrim"hello "
" hello " + $rtrim" hello"
" hello " + $trim"hello"
Both ends need cleanup? → use $trim
See $ltrim and $rtrim for one-sided trimming

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string)
Syntax{ $trim: { input: ..., chars: ... } }
Default behaviorRemove leading and trailing Unicode whitespace
Custom trimPass chars with characters to strip from both ends
null inputReturns null
Common stages$project, $addFields, $set
Whitespace
{
  $trim: {
    input: "$name"
  }
}

Default both-side trim

Custom chars
{
  $trim: {
    input: "$code",
    chars: "*"
  }
}

Strip * from both ends

Literal
{
  $trim: {
    input: "  hi  "
  }
}

Returns "hi"

Null input
{
  $trim: {
    input: null
  }
}

Returns null

Examples Gallery

Walk through a users collection with messy string fields and clean both ends with $trim.

📚 Clean User Names

Remove leading and trailing whitespace from imported user names using $project.

Sample Input Documents

Suppose you have a users collection with untrimmed name and email fields:

mongosh
[
  { "_id": 1, "name": "  Alice Smith  ", "email": "  alice@mail.com  " },
  { "_id": 2, "name": "\tBob Jones\t",   "email": "bob@mail.com " },
  { "_id": 3, "name": " Carol Lee ",    "email": " carol@mail.com" }
]

Example 1 — Basic $trim for Whitespace

Trim spaces and tabs from both ends of each user name:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      cleanName: {
        $trim: { input: "$name" }
      }
    }
  }
])

How It Works

  • Without chars, MongoDB removes leading and trailing whitespace (spaces, tabs, etc.).
  • Characters in the middle of the string are untouched.
  • This is the most common use case for normalizing user-entered text.

📈 Custom Character Trimming

Strip specific characters from both ends of codes and labels.

Example 2 — $trim with Custom chars

Remove leading and trailing * characters from product labels:

mongosh
db.products.aggregate([
  {
    $project: {
      label: 1,
      cleanLabel: {
        $trim: {
          input: "$label",
          chars: "*"
        }
      }
    }
  }
])

How It Works

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:

mongosh
db.users.aggregate([
  {
    $addFields: {
      emailNormalized: {
        $toLower: {
          $trim: { input: "$email" }
        }
      }
    }
  }
])

How It Works

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:

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

How It Works

$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.

Example 5 — $trim on a Literal String

Trim a fixed string inside an expression:

mongosh
db.users.aggregate([
  {
    $project: {
      demo: {
        $trim: { input: "  MongoDB  " }
      }
    }
  }
])

How It Works

The input can be a literal string, not just a field path. Useful inside nested expressions and for testing trim logic.

Bonus — Compare $trim vs $ltrim vs $rtrim

See how each trim operator affects the same string:

mongosh
db.users.aggregate([
  {
    $project: {
      original: "  MongoDB  ",
      fullTrim: {
        $trim: { input: "  MongoDB  " }
      },
      leftOnly: {
        $ltrim: { input: "  MongoDB  " }
      },
      rightOnly: {
        $rtrim: { input: "  MongoDB  " }
      }
    }
  }
])

// original:   "  MongoDB  "
// fullTrim:   "MongoDB"     ($trim both sides)
// leftOnly:   "MongoDB  "   ($ltrim start only)
// rightOnly:  "  MongoDB"   ($rtrim end only)

How It Works

Choose the right trim operator for your data. $trim is the go-to choice when both leading and trailing characters need cleanup.

🚀 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.

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $trim

Use these points when cleaning strings in MongoDB.

5
Core concepts
🔢 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.

Continue the Operator Series

Move on to $trunc for truncating numbers, or review $ltrim and $rtrim for one-sided trimming.

Next: $trunc →

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.

5 people found this page helpful