Introduction to MongoDB $ltrim Operator

The MongoDB $ltrim operator is used to remove specified characters from the left side of a string.

Syntax

The $ltrim operator uses the following syntax:

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

Where the parameters are:

  • input: A string expression from which to remove characters from the left side. Required.
  • chars: A character expression to remove from the left side. Optional. If not specified, spaces are removed from the left side by default.

Use Cases

The $ltrim operator can be used in the following use cases:

  • Removing spaces or other characters from the left side of a string.
  • Cleaning input data.

Examples

Assuming there is a collection called users that contains the following documents:

{ "_id": 1, "name": "   Alice", "age": 25 }
{ "_id": 2, "name": "Bob", "age": 30 }

The $ltrim operator can be used to remove spaces from the left side of the string as follows:

db.users.aggregate([
  {
    $project: {
      name: { $ltrim: { input: "$name" } },
      age: 1
    }
  }
])

The above aggregation operation will return the following results:

{ "_id": 1, "name": "Alice", "age": 25 }
{ "_id": 2, "name": "Bob", "age": 30 }

Conclusion

The MongoDB $ltrim operator is useful for removing specified characters from the left side of a string and is commonly used for cleaning input data and string processing.