0
0
MongodbHow-ToBeginner · 3 min read

How to Use $concat in Aggregation in MongoDB

In MongoDB aggregation, use the $concat operator to join multiple strings or fields into one string. It takes an array of expressions and returns their combined string. For example, { $concat: ["Hello, ", "$name"] } joins a literal and a field value.
📐

Syntax

The $concat operator takes an array of expressions and concatenates them into a single string.

  • Array elements: Can be string literals or field references.
  • Output: A single combined string.
json
{ $concat: [ <expression1>, <expression2>, ... ] }
💻

Example

This example shows how to concatenate a first name and last name fields with a space between them in an aggregation pipeline.

mongodb
db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      _id: 0
    }
  }
])
Output
[ { "fullName": "John Doe" }, { "fullName": "Jane Smith" } ]
⚠️

Common Pitfalls

Common mistakes when using $concat include:

  • Passing null or missing fields causes the whole result to be null.
  • Not including spaces or separators between fields results in joined words without spacing.
  • Using non-string fields without converting them to strings causes errors.

To avoid null results, use $ifNull or $toString to handle missing or non-string fields.

mongodb
/* Wrong: missing space and null field causes null output */
db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", "$lastName"] },
      _id: 0
    }
  }
])

/* Right: add space and handle null with $ifNull */
db.users.aggregate([
  {
    $project: {
      fullName: {
        $concat: [
          { $ifNull: ["$firstName", ""] },
          " ",
          { $ifNull: ["$lastName", ""] }
        ]
      },
      _id: 0
    }
  }
])
📊

Quick Reference

OperatorDescriptionExample
$concatJoins strings or fields into one string{ $concat: ["$field1", " ", "$field2"] }
$ifNullReplaces null or missing with a default value{ $ifNull: ["$field", "default"] }
$toStringConverts a value to string{ $toString: "$field" }

Key Takeaways

Use $concat with an array of strings or field references to join them in aggregation.
Handle null or missing fields with $ifNull to avoid null results in $concat.
Add spaces or separators explicitly as $concat does not add them automatically.
Convert non-string fields to strings with $toString before concatenation.
Use $project stage to create new concatenated fields in aggregation pipelines.