MongoDB $rtrim Operator

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

What Is $rtrim?

$rtrim is a MongoDB aggregation expression that removes characters from the end (right side) of a string. By default it strips whitespace; pass chars to strip a custom character set.

Remember
$rtrim ≈ String.trimEnd / rstrip

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

default → trim trailing whitespace
chars   → trim any of those characters from the end
null input → null

"hello   " → "hello"
"code***"  + chars "*" → "code"
UsePrefer
Trim the end only$rtrim
Trim the start only$ltrim
Trim both sides$trim

How to Use $rtrim in MongoDB

Pass the input string; optionally override which characters to remove.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to a string field (for example "$text").
  3. Optional: set chars to the characters you want stripped from the end.
  4. Include a space in chars if you need to trim spaces along with other characters.
PieceRequired?Role
inputYesString to trim
charsNoCharacter set to remove from the end (default: whitespace)
Result—New string with trailing matches removed

Pseudocode

Pseudocode
for each document:
    s = evaluate(input)
    if s is null:
        result = null
    else:
        set = chars or whitespace_set
        while s is not empty and last_char(s) is in set:
            remove last_char(s)
        result = s
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while cleaning trailing characters.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $rtrim: { input, chars? } }
DefaultTrailing whitespace (incl. null char)
charsSet of code points, not a whole suffix phrase
Null inputnull
vs $ltrim / $trimEnd only vs start only vs both

Live Preview

Pick an input and trim mode. Quotes show leftover spaces clearly.

Simulates $rtrim with default whitespace or a custom chars set.

Result
input = "hello   "
chars = (whitespace)
$rtrim → "hello"

{ cleaned: "hello" }

Worked Walkthrough — Spaces and Stars

Default mode strips trailing whitespace. Custom chars strips any listed character from the end.

Calculation
"hello   "
  → $rtrim → "hello"          // default whitespace

"code***"
  → $rtrim chars "*" → "code" // remove trailing *

"bye!! "
  → $rtrim chars "! " → "bye" // remove ! and spaces from end

"code*** "
  → $rtrim chars "*" → "code*** "  // ends with space; * never reached

Tip: chars is a set — order in the chars string does not matter.

MongoDB Examples

We use a small notes collection with a text field. First we trim trailing spaces, then we trim custom characters. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine three notes. Two have messy trailing characters; one has a null text field.

mongosh
db.notes.insertMany([
  { _id: 1, text: "hello   " },
  { _id: 2, text: "code***" },
  { _id: 3, text: null }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in notes. Run find() to see them:

mongosh
db.notes.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1Note id for this lesson
text"hello "String that may have trailing junk
Picture
"hello   "  → trailing spaces
"code***"   → trailing stars
null        → stays null after $rtrim

How It Works

  1. Insert once. insertMany adds three note documents.
  2. Trailing characters are real data. Spaces and * are stored until you trim them.
  3. find() shows the same shape. What you inserted is what you get back—ready for $rtrim next.

Example 2 — Trim Trailing Whitespace

Goal: add cleaned with default $rtrim (whitespace only).

mongosh
db.notes.aggregate([
  {
    $addFields: {
      cleaned: { $rtrim: { input: "$text" } }
    }
  }
]);

How It Works

  1. Read the stored string. input: "$text" is the note body.
  2. Default whitespace trim. Spaces/tabs/newlines at the end are removed.
  3. Note 1 cleaned. "hello " → "hello".
  4. Stars stay. * is not whitespace, so note 2 is unchanged. Null stays null.

Example 3 — Trim Custom Characters

Same notes, but remove trailing * characters with chars: "*".

mongosh
db.notes.aggregate([
  {
    $addFields: {
      cleaned: {
        $rtrim: {
          input: "$text",
          chars: "*"
        }
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the three notes from Example 1.
  2. Override the trim set. chars: "*" means only stars are removed from the end.
  3. Note 2 cleaned. Trailing *** are stripped → "code".
  4. Spaces untouched. Note 1 still has trailing spaces because space is not in chars.

Edge Cases & Pitfalls

Check these before using $rtrim in production pipelines.

set

chars is a character set

It is not “remove this whole suffix once.” Any listed character can be removed from the end, repeatedly.

block

A non-listed end char blocks trimming

If the string ends with a space and chars is "*", stars before that space stay. Include " " in chars when needed.

null

Null input → null

Missing/null strings return null. Guard with $ifNull if you want an empty string default.

both

Need both ends?

Use $trim instead of chaining only $rtrim.

Performance Notes

ApproachCostBest for
$rtrimO(trailing chars)Cleaning imported / padded strings
+ custom charsSimilarPadding markers like * / -
Trim at write timeOne-time costHot fields queried often

Trimming short strings is cheap. Prefer cleaning data on insert/update when every query would otherwise need the same $rtrim.

Key Takeaways

  • Role: remove characters from the end of a string.
  • Default: trailing whitespace.
  • chars: a set of code points, not a phrase.
  • Both sides? use $trim.

One line: $rtrim answers “what is this string without trailing junk?”—whitespace by default, or your chars set.

Frequently Asked Questions

$rtrim removes characters from the end of a string. By default it strips Unicode whitespace (and the null character). Pass chars to remove a custom set of characters instead.
Use { $rtrim: { input: <string>, chars: <optional string> } } inside stages like $project and $addFields. input is required; chars is optional.
$rtrim trims the right (end). $ltrim trims the left (start). $trim trims both sides.
A character set. MongoDB breaks chars into UTF code points and removes any of those characters from the end until it hits one that is not in the set.
If input is null, $rtrim returns null. It does not throw an error.
Trimming stops at the first character that is not in chars. If the string ends with a space and chars is "*", the stars behind the space are not reached.

Next: $sampleRate

Keep a random percentage of documents in a pipeline.

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