Aggregation Expressions
String Expressions
$concat, case folding, trim and substring operations on real fields.
String work in a pipeline is for display and keys, not for replacing $regex in $match. Concatenate, fold case, trim, slice. Pattern search on stored city is still equality or $regex in a filter.
db.users.aggregate([
{ $match: { name: "Rahul" } },
{
$project: {
_id: 0,
label: { $concat: ["$name", " · ", "$city"] },
emailFolded: { $toLower: "$email" }
}
}
]){ label: "Rahul · Bangalore", emailFolded: "rahul@example.com" }| Operator | Use |
|---|---|
| $concat | Join strings; null anywhere → null for the whole concat |
| $toLower / $toUpper | Fold case for a stable key |
| $trim | Strip whitespace; optional chars |
| $substrCP | Slice by code point — use this, not $substrBytes, for names |
| $split | Break on a delimiter → array |
{ $concat: [{ $ifNull: ["$name", ""] }, " <", { $ifNull: ["$email", "none"] }, ">"] }$replaceOne / $replaceAll exist when you must rewrite a stored string. $regexMatch in an expression is the aggregation cousin of query $regex. Neither belongs in every report — compute a field you will $group on ($toLower of city) rather than grouping on messy input.
Interview question
How do you build a display string in aggregation without nulls wiping it?
$concat joins fields. If any operand is null, the result is null — wrap each piece in $ifNull. $toLower / $toUpper for stable grouping keys. $substrCP for unicode-safe slices.