MongoDB $toLower Operator
MongoDB $toLower operator converts the given string to lowercase.
$toLower Operator in MongoDB
The $toLower operator in MongoDB is used in aggregation pipeline stages to convert a string to lowercase and return it.
This operator takes an expression as an input, this expression should resolve into a string for proper functioning. The $toLower operator in MongoDB has a well-defined behavior for ASCII characters.
Syntax
{ $toLower: <expression> }
Here, the argument passed in this operator can be any valid expression until it resolves to a string. If the entered argument resolves to null, then this operator will return an empty string ” “.
MongoDB $toLower Operator Examples
To understand it better, let’s look at some examples of MongoDB $toLower Operator.
In the following examples, we are working with:
Database: w3wiki
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
Using $toLower Operator Example
In this example, we are going to convert the value of the department field in lowercase.
Query:
db.employee.aggregate([
... {$match: {"name.first": "Aman"}},
... {$project: {dept: {$toLower: "$department"}}}])
Output:
Using $toLower Operator in embedded documents Example
In this example, we are going to convert the value of the name.first field in lowercase.
db.employee.aggregate([
... {$match: {department: "Development"}},
... {$project: {name: {$toLower: "$name.first"}}}])
KeyTakeAways About MongoDB $toLower Operator
- The MongoDB $toLower operator in is used in the aggregation pipeline stages to convert a string to lowercase and return the result.
- It accepts an expression as an argument, which can be any expression that resolves to a string.
- If the argument provided to $toLower resolves to null, it returns an empty string.
- $toLower only has a well-defined behavior for strings of ASCII characters.
- The $toLower operator is designed for use within the aggregation framework and is not used directly in update operations to modify documents in a collection.
Contact Us