0
0
MongodbHow-ToBeginner · 3 min read

How to Use $toUpper in Aggregation in MongoDB

In MongoDB aggregation, use the $toUpper operator inside a $project or other pipeline stage to convert string values to uppercase. It takes a string expression and returns the uppercase version of that string.
📐

Syntax

The $toUpper operator is used inside an aggregation pipeline stage like $project to convert a string field to uppercase.

Basic syntax:

  • { $toUpper: <string expression> }

Here, <string expression> can be a field path or any expression that returns a string.

json
{
  $project: {
    upperField: { $toUpper: "$fieldName" }
  }
}
💻

Example

This example shows how to convert the name field of documents to uppercase using $toUpper inside a $project stage.

mongodb
db.users.aggregate([
  {
    $project: {
      _id: 0,
      originalName: "$name",
      upperName: { $toUpper: "$name" }
    }
  }
])
Output
[ { "originalName": "alice", "upperName": "ALICE" }, { "originalName": "Bob", "upperName": "BOB" }, { "originalName": "charlie", "upperName": "CHARLIE" } ]
⚠️

Common Pitfalls

  • Using $toUpper on non-string fields causes errors or unexpected results.
  • Not using the $ prefix for field names inside $toUpper will treat the input as a literal string.
  • Trying to use $toUpper outside aggregation pipeline stages will not work.
json
/* Wrong: missing $ for field path */
{
  $project: {
    upperName: { $toUpper: "name" }  // treats "name" as literal string
  }
}

/* Right: use $ to refer to field */
{
  $project: {
    upperName: { $toUpper: "$name" }
  }
}
📊

Quick Reference

OperatorDescriptionUsage Example
$toUpperConverts a string to uppercase{ $toUpper: "$fieldName" }
$projectSelects fields and applies transformations{ $project: { upper: { $toUpper: "$name" } } }

Key Takeaways

Use $toUpper inside aggregation pipeline stages like $project to convert strings to uppercase.
Always prefix field names with $ inside $toUpper to refer to document fields.
Applying $toUpper on non-string fields can cause errors.
The operator returns the uppercase version of the input string.
Use $toUpper only within aggregation pipelines, not in regular queries.