Skip to content

Aggregation Expressions

String Expressions

$concat, case folding, trim and substring operations on real fields.

IntermediateAbout 5 minutes

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" }
    }
  }
])
Build a label. $trim before you concat.
{ label: "Rahul · Bangalore", emailFolded: "rahul@example.com" }
OperatorUse
$concatJoin strings; null anywhere → null for the whole concat
$toLower / $toUpperFold case for a stable key
$trimStrip whitespace; optional chars
$substrCPSlice by code point — use this, not $substrBytes, for names
$splitBreak on a delimiter → array
{ $concat: [{ $ifNull: ["$name", ""] }, " <", { $ifNull: ["$email", "none"] }, ">"] }
Nulls break $concat — wrap with $ifNull

$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?

Think about it first.