MongoDB $toUpper Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toUpper?

$toUpper is a MongoDB aggregation expression that converts a string to uppercase. Use it to normalize names, country codes, status labels, or group keys so mixed-case values match consistently.

Remember
$toUpper = toUpperCase() for aggregation

{ $toUpper: <expression> }

"john doe" → "JOHN DOE"
"us"       → "US"
null / missing → null

Pair with $group for case-insensitive keys
Opposite: $toLower
UsePrefer
String → UPPERCASE$toUpper
String → lowercase$toLower
Trim spaces first$trim then $toUpper

How to Use $toUpper in MongoDB

Pass a string expression, get uppercase text back, then use it for display or grouping.

  1. Choose an expression stage ($addFields or $project).
  2. Pass a string field (or nested string expression) to $toUpper.
  3. Keep the original field if you still need the mixed-case value.
  4. Optionally use the result as a $group key for case-insensitive counts.
PieceRequired?Role
$toUpperYesConvert string → uppercase
ExpressionYesString field, literal, or nested expression
$group keyNoMerge values that differ only by case

Pseudocode

Pseudocode
for each document:
    s = evaluate(expression)
    if s is null or missing:
        result = null
    else:
        result = uppercase(s)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing string-normalization expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toUpper: <expression> }
InputString (or expression that resolves to a string)
OutputUppercase string
Nullnull / missing → null
Group pattern_id: { $toUpper: "$department" }
Opposite$toLower

Live Preview

Watch $toUpper turn mixed-case text into uppercase. Pick a sample string and run the conversion.

Simulates $toUpper the same way as the mongosh examples below.

Result
input = "john doe"

$toUpper(input) → "JOHN DOE"

{ upperName: "JOHN DOE" }

Worked Walkthrough — Employee Name

One employee document stores name: "john doe". Goal: add an uppercase copy for a report header.

Calculation
Document:
  { _id: 1, name: "john doe", department: "engineering" }

$toUpper("$name")
  → "JOHN DOE"

Keep original:
  name: "john doe"
  upperName: "JOHN DOE"

MongoDB Examples

We use a small employees collection. First convert a name to uppercase, then group by uppercase department so mixed case merges. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine three employees. Names are lowercase; departments use mixed case on purpose so we can see grouping later.

mongosh
db.employees.insertMany([
  { _id: 1, name: "john doe", department: "engineering" },
  { _id: 2, name: "alice smith", department: "marketing" },
  { _id: 3, name: "bob jones", department: "Engineering" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in employees. Run find() to see them:

mongosh
db.employees.find()

Read each document like this:

Field in MongoDBExamplePlain English
_id1Document id (row number for this lesson)
name"john doe"Employee name (lowercase)
department"engineering" / "Engineering"Team name (mixed case on purpose)

How It Works

  1. Insert once. insertMany adds three employee documents to employees.
  2. Case is stored as written. engineering and Engineering are different strings until you normalize them.
  3. find() shows the same shape. What you inserted is what you get back—ready for $toUpper next.

Example 2 — Uppercase a Field

Goal: add an upperName field that is the uppercase form of name, without changing the original.

mongosh
db.employees.aggregate([
  {
    $addFields: {
      upperName: { $toUpper: "$name" }
    }
  }
]);

How It Works

  1. Read the stored name. John’s document has name: "john doe" from Example 1.
  2. Convert case. $toUpper: "$name" → "JOHN DOE".
  3. Keep all fields. $addFields adds upperName; the original name stays unchanged.

Example 3 — Case-Insensitive Group

Same employees, but group by uppercase department so engineering and Engineering count as one team.

mongosh
db.employees.aggregate([
  {
    $group: {
      _id: { $toUpper: "$department" },
      count: { $sum: 1 },
      employees: { $push: "$name" }
    }
  },
  { $sort: { count: -1 } }
]);

How It Works

  1. Same stored documents. Still using the three employees from Example 1.
  2. Normalize the key. $toUpper turns both department spellings into "ENGINEERING".
  3. Group and count. $group merges John and Bob under one bucket; Marketing stays alone.
  4. Easy check. Engineering should show count: 2.

Edge Cases & Pitfalls

Check these before using $toUpper in production pipelines.

type

Input must be a string

Numbers and ObjectIds are not strings. Convert with $toString first if needed.

null

Null and missing become null

Missing fields return null, not an empty string. Guard with $ifNull if you need a default.

spaces

Spaces are not removed

$toUpper only changes letter case. Trim first with $trim when padding spaces matter.

locale

Locale rules can differ

Most Latin letters upper-case as expected. For special locale casing needs, test your real data and consider collation for comparisons.

Performance Notes

ApproachCostBest for
$toUpper alonePer-document string workDisplay / export fields
$toUpper as $group keyConvert + groupCase-insensitive counts
Normalize lateFewer conversionsPipelines that filter first

Case conversion is cheap compared with large sorts or joins. Filter early with $match when only some documents need uppercase text.

Key Takeaways

  • Role: string → UPPERCASE in aggregation.
  • Normalize: codes, labels, and report headers.
  • Grouping: use as $group _id for case-insensitive keys.
  • Opposite: $toLower for lowercase convention.

One line: $toUpper answers “what is this string in uppercase?”—for labels, codes, and fair grouping.

Frequently Asked Questions

$toUpper converts a string to uppercase inside an aggregation pipeline. Use it in expression stages such as $project and $addFields.
Use { $toUpper: <expression> }. The expression can be a field path like "$name", a literal string, or another string expression.
$toUpper makes all letters uppercase ("john" → "JOHN"). $toLower makes them lowercase. Pick one convention and stay consistent.
Use it for country codes, status labels, display headers, and case-insensitive grouping keys when your convention is uppercase.
$toUpper returns null when the input is null or the field is missing. It does not throw an error for null input.
Yes for the idea. Think of $toUpper as MongoDB’s aggregation version of toUpperCase()—run it in the pipeline, not as a standalone find() filter.

Next: $trim

Remove leading and trailing whitespace from strings in a pipeline.

$trim tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful