MongoDB $rtrim Operator

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 4 Examples
String Operations

What You’ll Learn

The $rtrim operator removes trailing characters from a string in MongoDB aggregation expressions. By default it strips whitespace from the right; optionally you can specify which characters to remove.

01

Right Trim

End of string only.

02

Syntax

input + optional chars.

03

Whitespace

Default trim behavior.

04

Custom Chars

Strip suffixes like /.

05

Use Cases

URLs, imports, codes.

06

vs $ltrim

Right vs left end.

Definition and Usage

In MongoDB’s aggregation framework, the $rtrim operator trims characters from the right side of a string. For example, "MongoDB " becomes "MongoDB" when you trim trailing whitespace. This is useful when cleaning imported data, normalizing URLs, or removing trailing punctuation from codes.

Think of $rtrim as MongoDB’s pipeline version of trimming only the end of a string — similar in spirit to JavaScript’s String.prototype.trimEnd(), with an optional custom character set.

💡
Beginner Tip

$rtrim only affects the right end. Leading spaces stay in place. Use $trim to clean both sides, or $ltrim for the left end only.

📝 Syntax

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

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

Common Patterns

mongosh
// Trim trailing whitespace (default)
{ $rtrim: { input: "$name" } }

// Trim specific trailing characters
{ $rtrim: {
    input: "$url",
    chars: "/"
}}

// Trim a literal string
{ $rtrim: { input: "hello   " } }

Syntax Rules

  • input — required; the string expression to trim (field reference or literal).
  • chars — optional; characters to remove from the right. If omitted, whitespace is trimmed.
  • MongoDB removes matching characters repeatedly from the end until a non-matching character is found.
  • If input is null, the result is null.
  • Use inside $project, $addFields, or $set.

💡 $rtrim vs $ltrim vs $trim

" hello " + $ltrim"hello "
" hello " + $rtrim" hello"
" hello " + $trim"hello"
Only trailing cleanup? → use $rtrim

⚡ Quick Reference

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

Default right trim

Custom chars
{
  $rtrim: {
    input: "$url",
    chars: "/"
  }
}

Strip trailing /

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

Returns "hi"

Null input
{
  $rtrim: {
    input: null
  }
}

Returns null

Examples Gallery

Walk through a sites collection with messy string fields and clean trailing characters with $rtrim.

📚 Clean Site Names

Remove trailing whitespace from imported site names using $project.

Sample Input Documents

Suppose you have a sites collection with untrimmed name and url fields:

mongosh
[
  {
    "_id": 1,
    "name": "CodeToFun   ",
    "url": "https://codetofun.com///"
  },
  {
    "_id": 2,
    "name": "MongoDB Docs\t",
    "url": "https://mongodb.com/docs/"
  },
  {
    "_id": 3,
    "name": "Example Site  ",
    "url": "https://example.com"
  }
]

Example 1 — Basic $rtrim for Trailing Whitespace

Trim spaces and tabs from the end of each site name:

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

How It Works

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

📈 Custom Character Trimming

Strip trailing slashes from URL paths for consistent linking.

Example 2 — $rtrim with Custom chars

Remove trailing / characters from URL values:

mongosh
db.sites.aggregate([
  {
    $project: {
      url: 1,
      cleanUrl: {
        $rtrim: {
          input: "$url",
          chars: "/"
        }
      }
    }
  }
])

How It Works

The chars argument defines which characters to strip from the right. MongoDB removes them one by one from the end until it hits a character not in the set.

Example 3 — Clean Both Name and URL in One Stage

Apply $rtrim to multiple fields in a single $addFields stage:

mongosh
db.sites.aggregate([
  {
    $addFields: {
      name: {
        $rtrim: { input: "$name" }
      },
      url: {
        $rtrim: {
          input: "$url",
          chars: "/"
        }
      }
    }
  }
])

How It Works

$addFields overwrites the existing fields with cleaned values. Use this when you want to normalize data in place before downstream stages or export.

Example 4 — $rtrim on a Literal String

Trim a fixed string inside an expression:

mongosh
db.sites.aggregate([
  {
    $project: {
      demo: {
        $rtrim: { 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 $rtrim vs $ltrim vs $trim

See how each trim operator affects the same string:

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

// leftOnly:  "MongoDB  "
// rightOnly: "  MongoDB"

How It Works

$rtrim is precise when you only need to fix the end of a string. For both sides, use $trim when that page is available in the series.

🚀 Use Cases

  • Import cleanup — remove trailing spaces from CSV or spreadsheet data loaded into MongoDB.
  • URL normalization — strip trailing slashes so links compare and deduplicate correctly.
  • Display formatting — prepare clean labels in $project for reports and APIs.
  • Consistent matching — trim before comparisons so "active " matches "active" on the right side.

🧠 How $rtrim 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 the right

Strips matching characters from the end until the first non-matching character from the right.

Trim
=

Clean right edge

The expression returns the string with trailing characters removed.

Conclusion

The $rtrim operator is a practical string-cleaning tool for MongoDB aggregation pipelines. Use it to remove trailing whitespace or custom suffix characters from field values before display, matching, or further string operations.

Remember: input is required, chars is optional, and only the right side is affected. For full whitespace cleanup on both ends, use $trim. Next in the series: $sampleRate.

💡 Best Practices

✅ Do

  • Use $rtrim when only trailing characters need removal
  • Omit chars for standard whitespace cleanup
  • Pass chars: "/" to normalize URL paths
  • Clean strings in $addFields before matching or grouping
  • Pair with $ltrim or $trim when both ends need work

❌ Don’t

  • Expect $rtrim to remove leading spaces (use $ltrim or $trim)
  • Use $rtrim as a pipeline stage — it is an expression operator
  • Forget that null input returns null
  • Confuse chars with a single 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 $rtrim

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

vs $ltrim

Right vs left.

Compare
📑 05

Data Cleaning

URLs & imports.

Use case

❓ Frequently Asked Questions

$rtrim removes trailing characters from a string. By default it strips whitespace from the right side. You can optionally pass a chars argument to remove specific characters instead.
The syntax is { $rtrim: { input: <expression>, chars: <optional string> } }. The input is required. If chars is omitted, MongoDB trims Unicode whitespace from the right.
$rtrim removes characters from the right (end) of a string. $ltrim removes from the left (start). $trim removes from both sides. Use $rtrim when only trailing characters need cleaning.
If the input expression is null, $rtrim returns null. It does not throw an error.
Use $rtrim inside expression stages such as $project, $addFields, and $set when cleaning imported data, normalizing URLs, or preparing strings for display or comparison.

Continue the Operator Series

Move on to $sampleRate for probabilistic sampling, or review $ltrim for leading character cleanup.

Next: $sampleRate →

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