MongoDB $ltrim Operator

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

What You’ll Learn

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

01

Left Trim

Start of string only.

02

Syntax

input + optional chars.

03

Whitespace

Default trim behavior.

04

Custom Chars

Strip prefixes like #.

05

Use Cases

Data cleaning, codes.

06

vs $trim

Left vs both sides.

Definition and Usage

In MongoDB’s aggregation framework, the $ltrim operator trims characters from the left side of a string. For example, " MongoDB" becomes "MongoDB" when you trim leading whitespace. This is useful when cleaning imported CSV data, normalizing product codes, or preparing strings for matching and display.

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

💡
Beginner Tip

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

📝 Syntax

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

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

Common Patterns

mongosh
// Trim leading whitespace (default)
{ $ltrim: { input: "$name" } }

// Trim specific leading characters
{ $ltrim: {
    input: "$code",
    chars: "#0"
}}

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

Syntax Rules

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

💡 $ltrim vs $rtrim vs $trim

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

⚡ Quick Reference

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

Default left trim

Custom chars
{
  $ltrim: {
    input: "$code",
    chars: "#"
  }
}

Strip # prefix

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

Returns "hi"

Null input
{
  $ltrim: {
    input: null
  }
}

Returns null

Examples Gallery

Walk through a products collection with messy string fields and clean leading characters with $ltrim.

📚 Clean Product Names

Remove leading whitespace from imported product names using $project.

Sample Input Documents

Suppose you have a products collection with untrimmed name and sku fields:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "   Notebook", "sku": "###NB-001" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "\tPen Pack", "sku": "##PP-002" },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "  Stapler", "sku": "#ST-003" }
]

Example 1 — Basic $ltrim for Leading Whitespace

Trim spaces and tabs from the start of each product name:

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

How It Works

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

📈 Custom Character Trimming

Strip specific prefix characters like # from SKU codes.

Example 2 — $ltrim with Custom chars

Remove leading # characters from SKU values:

mongosh
db.products.aggregate([
  {
    $project: {
      sku: 1,
      cleanSku: {
        $ltrim: {
          input: "$sku",
          chars: "#"
        }
      }
    }
  }
])

How It Works

The chars argument defines which characters to strip from the left. MongoDB removes them one by one from the start until it hits a character not in the set (like N or P).

Example 3 — Clean Both Name and SKU in One Stage

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

mongosh
db.products.aggregate([
  {
    $addFields: {
      name: {
        $ltrim: { input: "$name" }
      },
      sku: {
        $ltrim: {
          input: "$sku",
          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.

Example 4 — $ltrim on a Literal String

Trim a fixed string inside an expression:

mongosh
db.products.aggregate([
  {
    $project: {
      demo: {
        $ltrim: { 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 — Chain with $trim for Full Cleanup

When both leading and trailing whitespace matter, use $trim instead:

mongosh
db.products.aggregate([
  {
    $project: {
      name: 1,
      fullyClean: {
        $trim: { input: "$name" }
      },
      leftOnly: {
        $ltrim: { input: "$name" }
      }
    }
  }
])

// name: "  Notebook  "
//   fullyClean → "Notebook"   ($trim both sides)
//   leftOnly   → "Notebook  " ($ltrim start only)

How It Works

Choose the right trim operator for your data. $ltrim is precise when you only need to fix the start of a string.

🚀 Use Cases

  • Import cleanup — remove leading spaces from CSV or spreadsheet data loaded into MongoDB.
  • SKU and code normalization — strip prefix characters like # or 0 from identifiers.
  • Display formatting — prepare clean labels in $project for reports and APIs.
  • Consistent matching — trim before comparisons so " active" matches "active" on the left side.

🧠 How $ltrim 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 left

Strips matching characters from the start until the first non-matching character.

Trim
=

Clean left edge

The expression returns the string with leading characters removed.

Conclusion

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

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

💡 Best Practices

✅ Do

  • Use $ltrim when only leading characters need removal
  • Omit chars for standard whitespace cleanup
  • Pass chars to strip known prefix symbols like #
  • Clean strings in $addFields before matching or grouping
  • Use $trim when both ends need cleaning

❌ Don’t

  • Expect $ltrim to remove trailing spaces (use $rtrim or $trim)
  • Use $ltrim as a pipeline stage — it is an expression operator
  • Forget that null input returns null
  • Confuse chars with a single prefix string — it is a character set
  • Trim numbers directly — convert with $toString first if needed

Key Takeaways

Knowledge Unlocked

Five things to remember about $ltrim

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

Left vs both.

Compare
📑 05

Data Cleaning

Imports & SKUs.

Use case

❓ Frequently Asked Questions

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

Continue the Operator Series

Move on to $map for transforming array elements, or review $concat for joining strings.

Next: $map →

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