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
Advertisement728 x 90
Common Errors & Troubleshooting
$concatthrowing an error on anull/missing field — unlike SQL's typical NULL-tolerant concatenation,$concatreturnsnullfor the whole expression if ANY input isnull, rather than treating it as an empty string.- Applying
$toUpper/$toLowerto 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/$concatonly work inside pipeline stages like$projector$group— they can't be used inside a plainfind()query filter.
Key Takeaways
- These operators only run inside expressions (like
$project) — they never modify the stored document. $concatmixes literal strings and"$field"references freely, in any order.
Advertisement320 x 100