MongoDB $toUpper Operator
MongoDB $toUpper operator converts the given string to uppercase.
$toUpper Operator in MongoDB
The $toUpper Operator in MongoDB is used in the aggregation pipeline stages to convert a string to uppercase and return the result.
It can also be used on non-string fields if they can be converted to a string but Its behavior for non-ASCII characters may not be as expected.
Syntax
{ $toUpper: <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 $toUpper Operator
To understand it better, let’s look at some examples of MongoDB $toUpper 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 $toUpper Operator Example
In this example, we are going to convert the value of the department field in uppercase and assign the result of the $toUpper operator as a value of dept field.
db.employee.aggregate([
... {$project: {dept: {$toUpper: "$department"}}}])
Using $toUpper Operator in the Embedded Document Example
In this example, we are going to convert the value of the name.first field in uppercase and assign the result of the $toUpper operator as a value of firstName field.
db.employee.aggregate([
... {$project: {firstName: {$toUpper: "$name.first"}}}])
KeyTakeAways About MongoDB $toUpper Operator
- The $toUpper operator is used in the aggregation pipeline stages to convert a string to uppercase and return the result.
- It accepts an expression as an argument, which can be any expression that resolves to a string. This means $toUpper can be used on non-string fields as well, as long as they can be converted to a string.
- If the argument provided to $toUpper resolves to null, it will return an empty string.
- Its behavior for non-ASCII characters may not be as expected.
- The $toUpper operator is designed for use within the aggregation framework and cannot be used directly in update operations to modify documents in a collection.
- The $toLower operator, which converts a string to lowercase works similarly to $toUpper.
Contact Us