Introduction to MongoDB $toUpper Operator

The Mongodb $toUpper operator is a string aggregation operator that converts a string to uppercase. It can be used in the $project and $addFields stages of a Mongodb aggregation pipeline, and helps users to process and transform string data.

Syntax

The syntax of the $toUpper operator is as follows:

{ $toUpper: <expression> }

Here, <expression> represents the string expression to be converted to uppercase, which can be a field name, constant, or other expression.

Use Cases

The $toUpper operator is commonly used in the following scenarios:

  • Converting a string to uppercase for string matching or comparison.
  • Formatting strings to unify case for easier processing.
  • Processing string data to meet specific business needs.

Examples

Here are two examples of using the $toUpper operator.

Example 1

Suppose we have a user collection that contains the name and email address of each user. We want to convert all email addresses to uppercase for case-insensitive comparison. We can use the following aggregation pipeline:

db.users.aggregate([
  { $project: { _id: 0, name: 1, email: { $toUpper: "$email" } } }
])

This aggregation pipeline uses the $project operator to project the user’s name and email address converted to uppercase. The final output is as follows:

{ "name": "Alice", "email": "[email protected]" }
{ "name": "Bob", "email": "[email protected]" }
{ "name": "Charlie", "email": "[email protected]" }

Example 2

Suppose we have an order collection that contains the product name and price of each order. We want to convert all product names to uppercase and sort them by name in a query. We can use the following aggregation pipeline:

db.orders.aggregate([
  { $project: { _id: 0, product: { $toUpper: "$product" }, price: 1 } },
  { $sort: { product: 1 } }
])

This aggregation pipeline uses the $project operator to convert the product name to uppercase and sorts by name. The final output is as follows:

{ "product": "APPLES", "price": 2.99 }
{ "product": "BANANAS", "price": 1.99 }
{ "product": "ORANGES", "price": 3.99 }

Conclusion

The Mongodb $toUpper operator is a convenient string aggregation operator that converts a string to uppercase for string comparison and processing. It is commonly used in scenarios that require formatting and processing of strings and can be combined with other string aggregation operators such as $match and $regexMatch.