🍃 MongoDB Tutorial

MongoDB String Expression Operators: $toUpper, $toLower, $concat

Learn how to transform text inside a MongoDB aggregation pipeline with $toUpper, $toLower and $concat — including how to build a new string field from multiple values.

String Expression Operators in Aggregation

These operators transform text values inside a $project stage, letting you reshape strings on the fly without changing the underlying stored data.

$toUpper

db.employees.aggregate([
  { $project: { nameUpper: { $toUpper: "$name" } } }
])

db.employees.aggregate([
  { $match: { gender: "M" } },
  { $project: { nameUpper: { $toUpper: "$name" } } }
])

$toLower

db.employees.aggregate([
  { $project: { emailLower: { $toLower: "$email" } } }
])

$concat — Build a New String

Joins two or more strings (literal text and/or field values) into a single result.

db.employees.aggregate([
  { $project: { name: { $concat: ["My name is = ", "$name"] } } }
])

db.employees.aggregate([
  { $project: { email: 1, name: { $concat: ["My name is = ", "$name"] } } }
])

db.employees.aggregate([
  {
    $project: {
      email: 1,
      mgrname: {
        $concat: ["My reporting manager name is = ", "$reportinmgr.mgrname"]
      }
    }
  }
])
// $concat works with embedded document fields too

Common Errors & Troubleshooting

  • $concat throwing an error on a null/missing field — unlike SQL's typical NULL-tolerant concatenation, $concat returns null for the whole expression if ANY input is null, rather than treating it as an empty string.
  • Applying $toUpper/$toLower to a non-string field — these operators expect a string; running them against a number or date field throws a type error.
  • Forgetting these only run inside expressions — $toUpper/$toLower/$concat only work inside pipeline stages like $project or $group — they can't be used inside a plain find() query filter.

Key Takeaways

  • These operators only run inside expressions (like $project) — they never modify the stored document.
  • $concat mixes literal strings and "$field" references freely, in any order.