How to Use $toLower in Aggregation in MongoDB
In MongoDB aggregation, use the
$toLower operator inside a $project or $addFields stage to convert string values to lowercase. It takes a string expression and returns the lowercase version of that string.Syntax
The $toLower operator is used within an aggregation pipeline stage like $project or $addFields. It converts a string expression to lowercase.
{ $toLower: <string expression> }: Converts the input string to lowercase.
mongodb
{
$project: {
lowerCaseField: { $toLower: "$originalField" }
}
}Example
This example shows how to convert the name field of documents to lowercase using $toLower inside a $project stage.
mongodb
db.users.aggregate([
{
$project: {
_id: 0,
originalName: "$name",
lowerCaseName: { $toLower: "$name" }
}
}
])Output
[
{ "originalName": "Alice", "lowerCaseName": "alice" },
{ "originalName": "BOB", "lowerCaseName": "bob" },
{ "originalName": "Charlie", "lowerCaseName": "charlie" }
]
Common Pitfalls
- Passing a non-string value to
$toLowerwill cause an error. Always ensure the field is a string. - Using
$toLoweroutside of an aggregation pipeline stage like$projector$addFieldsis invalid. - Remember that
$toLowerdoes not modify the original field unless you overwrite it explicitly.
mongodb
/* Wrong: Using $toLower outside aggregation stage */ { lowerName: { $toLower: "$name" } } /* Right: Use inside $project or $addFields */ { $project: { lowerName: { $toLower: "$name" } } }
Quick Reference
| Operator | Description | Example Usage |
|---|---|---|
| $toLower | Converts a string to lowercase | { $toLower: "$fieldName" } |
| $project | Selects fields and can transform them | { $project: { lower: { $toLower: "$name" } } } |
| $addFields | Adds or modifies fields in documents | { $addFields: { lower: { $toLower: "$name" } } } |
Key Takeaways
Use $toLower inside aggregation stages like $project or $addFields to convert strings to lowercase.
Ensure the input to $toLower is a string to avoid errors.
$toLower returns a new lowercase string and does not modify the original field unless reassigned.
You cannot use $toLower outside of an aggregation pipeline stage.
Combine $toLower with other aggregation operators to transform data effectively.