MongoDB $ltrim Operator

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

What Is $ltrim?

$ltrim is a MongoDB aggregation expression that removes characters from the left (start) of a string. Default: leading whitespace. Optional chars: a set of characters to strip instead.

Remember
$ltrim = trim from the left only

{ $ltrim: { input: <string> } }
{ $ltrim: { input: <string>, chars: <string> } }

default chars → whitespace (incl. null)
custom chars  → each character is a trim candidate (a set, not one substring)

{ $ltrim: { input: "  hello" } }           → "hello"
{ $ltrim: { input: "00042", chars: "0" } } → "42"

null / missing input → null
right side untouched
NeedPrefer
Trim left only$ltrim
Trim right only$rtrim
Trim both sides$trim

How to Use $ltrim in MongoDB

Point at a string field, optionally set chars, then store the cleaned value in a stage.

  1. Choose an expression stage ($addFields or $project).
  2. Pass the string: { $ltrim: { input: "$label" } }.
  3. For custom leading characters, add chars (for example "0").
  4. Remember: trimming stops at the first character not listed in chars.
PieceRequired?Role
inputYesString to clean
charsNoCharacter set to strip from the left
Result—New string (right side unchanged)

Pseudocode

Pseudocode
s = evaluate(input)
if s is null or missing:
    result = null
else:
    set = chars if provided else whitespace
    while s starts with a character in set:
        remove that leading character
    result = s
emit { ..., field: result }

Cheat Sheet

Keep these facts handy while cleaning leading characters.

TopicDetail
TypeAggregation expression (not a find filter)
Default{ $ltrim: { input: "$label" } }
Custom{ $ltrim: { input: "$code", chars: "0" } }
charsSet of characters, not one fixed prefix
Related$rtrim, $trim
Sample check" hello" → "hello"

Live Preview

Watch $ltrim remove leading spaces or leading zeros.

Simulates default whitespace trim or a custom chars set.

Result
input = "  hello"
chars = whitespace (default)

$ltrim → "hello"

Worked Walkthrough — Leading Spaces

A label is stored as " hello" (two leading spaces). We want "hello".

Calculation
input: "  hello"

$ltrim default (whitespace):
  char[0] = ' ' → trim
  char[1] = ' ' → trim
  char[2] = 'h' → stop (not whitespace)

Result:
  "hello"

Trailing spaces (if any) would stay — $ltrim only touches the left.

MongoDB Examples

We use one document with a padded label and a zero-padded code. First we store it, then we trim spaces, then we trim leading zeros. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one row with a messy label "  hello" and a code "00042".

mongosh
db.labels.insertOne({
  _id: 1,
  label: "  hello",
  code: "00042"
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in labels. Run find() to see it:

mongosh
db.labels.find()

Read that document like this:

Field in MongoDBValuePlain English
label" hello"Text with leading spaces
code"00042"Code with leading zeros
Picture
"  hello"  --$ltrim-->  "hello"
"00042"    --$ltrim chars "0"-->  "42"

How It Works

  1. Insert once. insertOne adds a single document to labels.
  2. Store messy strings. Leading spaces and zeros are common import problems.
  3. find() shows the same shape. Ready for $ltrim next.

Example 2 — Trim Spaces

Goal: remove leading whitespace from label.

mongosh
db.labels.aggregate([
  {
    $addFields: {
      cleanLabel: {
        $ltrim: { input: "$label" }
      }
    }
  }
]);

How It Works

  1. Read the string. input: "$label" is " hello".
  2. Default trim. No chars means strip leading whitespace.
  3. Stop at h. The first non-whitespace character ends trimming.
  4. Keep original too. $addFields adds cleanLabel without deleting label.

Example 3 — Trim Zeros

Goal: strip leading 0 characters from code using a custom chars set.

mongosh
db.labels.aggregate([
  {
    $project: {
      code: 1,
      cleanCode: {
        $ltrim: {
          input: "$code",
          chars: "0"
        }
      }
    }
  }
]);

How It Works

  1. Set a custom char set. chars: "0" means “trim zeros from the left”.
  2. Strip while matching. Three leading 0s are removed.
  3. Stop at 4. 4 is not in chars, so trimming ends → "42".
  4. Project a clean shape. Output shows original code and cleaned code.

Edge Cases & Pitfalls

Check these before using $ltrim in production pipelines.

chars

chars is a set, not a prefix

chars: "01" trims any mix of 0 and 1 from the left—not only the exact substring "01".

block

First non-matching char stops trim

If the string starts with a space and chars is "0", nothing is removed. Include the space in chars, or trim whitespace first.

side

Right side is untouched

Trailing spaces stay. Use $rtrim or $trim when you need the other end too.

null

Null input returns null

Missing or null strings become null, not an empty string.

Performance Notes

ApproachCostBest for
$ltrim in pipelineCheap per documentCleaning imported strings
Trim on writeWrite cost, cheaper readsFields queried/compared often
Very long stringsScans from the leftStill fine for normal text fields

Trimming is inexpensive compared with large sorts or joins. Clean early when later stages depend on exact string matches.

Key Takeaways

  • Role: remove leading characters from a string.
  • Default: whitespace; optional chars set.
  • Stops early: first non-matching character ends the trim.
  • Siblings: $rtrim (right), $trim (both).

One line: $ltrim answers “what does this string look like without its leading junk?”

Frequently Asked Questions

$ltrim removes characters from the beginning (left) of a string. By default it strips whitespace. Optionally pass chars to remove a set of custom characters instead. Use it inside aggregation stages such as $project and $addFields.
The syntax is { $ltrim: { input: <string>, chars: <optional string> } }. input is required. If chars is omitted, MongoDB trims Unicode whitespace (including null) from the left.
$ltrim removes from the left only. $rtrim removes from the right only. $trim removes from both sides. Use $ltrim when only leading characters need cleaning.
A character set. MongoDB treats each UTF code point in chars as a character that can be trimmed from the start, not as one fixed prefix string.
If input is null or refers to a missing field, $ltrim returns null. It does not throw an error.
Trimming stops at the first character that is not in chars. If the string starts with a space and chars is "0", the leading space blocks zero-trimming. Include the space in chars, or trim whitespace first.

Next: $map

Transform every element of an array with an aggregation expression.

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