Skip to content

$trim

The $trim operator removes specified characters from the beginning and end of a string.


📌 Syntax

{
  "$trim": {
    "input": <expression>,
    "chars": <charsToTrim>
  }
}
  • input: The string to trim
  • chars: The characters to remove (optional, defaults to whitespace)

✅ Base Example 1 – Trim Whitespace

📥 Input Document

{ "username": "  alice123  " }

📌 Expression

{
  "$trim": { "input": "$username" }
}

📤 Output

"alice123"

✅ Base Example 2 – Trim Slashes from Path

📥 Input Document

{ "path": "/products/shoes/" }

📌 Expression

{
  "$trim": {
    "input": "$path",
    "chars": "/"
  }
}

📤 Output

"products/shoes"

🧱 Ecommerce Example – Clean Category Labels

📌 Pipeline

[
  { "$unwind": "$items" },
  {
    "$project": {
      "cleanCategory": {
        "$trim": {
          "input": "$items.category",
          "chars": "-"
        }
      },
      "product": "$items.name"
    }
  }
]

📥 Input Document

{
  "items": [
    { "name": "Sneakers", "category": "--footwear--" },
    { "name": "Watch", "category": "--accessories--" }
  ]
}

📤 Output

[
  { "cleanCategory": "footwear", "product": "Sneakers" },
  { "cleanCategory": "accessories", "product": "Watch" }
]

🔧 Common Use Cases

  • Strip extra characters (slashes, dashes, spaces)
  • Normalize labels and IDs
  • Clean user input

  • $ltrim, $rtrim, $toLower, $toUpper

🧠 Notes

  • If chars is omitted, whitespace is trimmed by default.
  • Useful before comparisons and filtering.