MongoDB $concat Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
String Operations

What You’ll Learn

The $concat operator joins multiple string values into one string in MongoDB aggregation pipelines. Use it to build full names, formatted labels, addresses, and display-friendly output from separate fields.

01

Join Strings

Combine fields + literals.

02

Syntax

Array of expressions.

03

Separators

Add spaces, commas, etc.

04

$project Stage

Create display fields.

05

Use Cases

Names, reports, labels.

06

Null Safety

Guard with $ifNull.

Definition and Usage

In MongoDB’s aggregation framework, the $concat operator concatenates an array of string expressions into a single string. For example, { $concat: ["$firstName", " ", "$lastName"] } produces "John Doe" when firstName is John and lastName is Doe.

💡
Beginner Tip

Include literal separators like " " (space), ", " (comma-space), or "-" between field references. Without them, values are joined with no gap.

📝 Syntax

The $concat operator takes an array of string expressions:

mongosh
{ $concat: [ <expression1>, <expression2>, ... ] }

Syntax Rules

  • $concat — returns one string built from all array elements.
  • Expressions — field references ("$firstName"), literals (" "), or nested string expressions.
  • Use inside stages like $project, $addFields, or $set.
  • If any expression is null, the entire result is null.
  • Non-string values (like numbers) must be converted with $toString first.

⚠️ Null Values Return Null

If any part of the concatenation is null, the whole result becomes null:

$concat: ["John", " ", "Doe"]"John Doe"
$concat: ["John", " ", null]null
Fix: { $ifNull: ["$lastName", ""] } per field

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string)
Syntax{ $concat: [ expr1, expr2, ... ] }
Input typesStrings (use $toString for numbers)
Null behaviorAny null → entire result is null
Common stages$project, $addFields, $set
Full name
{
  $concat: ["$first", " ", "$last"]
}

Join with space

Label
{
  $concat: ["Order #", "$id"]
}

Prefix + field

Null safe
$ifNull per field

Prevent null output

vs Arrays
$concatArrays

Joins arrays, not strings

Examples Gallery

Build full names, formatted addresses, and null-safe labels using $concat in aggregation pipelines.

📚 Combine Fields

Use a students collection and build a fullName field with $project.

Sample Input Documents

Suppose you have a students collection with separate name fields:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "firstName": "John",    "lastName": "Doe",     "grade": "A" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "firstName": "Alice",   "lastName": "Smith",   "grade": "B" },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "firstName": "Michael", "lastName": "Johnson", "grade": "C" }
]

Example 1 — Basic $concat for Full Name

Concatenate firstName and lastName with a space separator:

mongosh
db.students.aggregate([
  {
    $project: {
      fullName: { $concat: [ "$firstName", " ", "$lastName" ] },
      grade: 1
    }
  }
])

How It Works

MongoDB evaluates each array element left to right and joins them into one string. The literal " " inserts a space between first and last names.

📈 Practical Patterns

Handle missing values, format addresses, and combine numbers with strings.

Example 2 — Null-Safe Concatenation with $ifNull

Prevent a missing lastName from nullifying the entire result:

mongosh
db.students.aggregate([
  {
    $project: {
      fullName: {
        $concat: [
          { $ifNull: [ "$firstName", "" ] },
          " ",
          { $ifNull: [ "$lastName", "" ] }
        ]
      },
      grade: 1
    }
  }
])

// firstName: "John", lastName: null  → fullName: "John "
// firstName: null,   lastName: "Doe" → fullName: " Doe"

How It Works

$ifNull replaces missing fields with an empty string so $concat can still produce output. Trim with $trim if trailing spaces matter.

Example 3 — Build a Formatted Address

Join multiple address parts with commas for report output:

mongosh
db.customers.aggregate([
  {
    $project: {
      name: 1,
      fullAddress: {
        $concat: [
          { $ifNull: [ "$street", "" ] },
          ", ",
          { $ifNull: [ "$city", "" ] },
          ", ",
          { $ifNull: [ "$state", "" ] },
          " ",
          { $ifNull: [ "$zip", "" ] }
        ]
      }
    }
  }
])

// → "123 Main St, Springfield, IL 62701"

How It Works

Mix field references and literal separators freely. This pattern is common for CSV exports, mailing labels, and dashboard display fields.

Example 4 — Concatenate Numbers with $toString

$concat only accepts strings. Convert numbers before joining:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderLabel: {
        $concat: [
          "Order #",
          { $toString: "$orderId" },
          " — $",
          { $toString: "$total" }
        ]
      }
    }
  }
])

// orderId: 1042, total: 59.99 → "Order #1042 — $59.99"

How It Works

Wrap numeric fields with $toString before passing them to $concat. For formatted currency, consider $round before converting.

🚀 Use Cases

  • Data formatting — build composite display fields from separate string columns.
  • Report generation — create readable labels for exports and dashboards.
  • Full name assembly — join first, middle, and last name fields with separators.
  • Textual analysis — merge text fields before search or pattern matching downstream.

🧠 How $concat Works

1

MongoDB evaluates each expression

Field references and literals in the array are resolved to string values (or null).

Input
2

$concat joins them in order

Values are appended left to right with no automatic separator. If any value is null, the result is null.

Join
3

The combined string is stored

The result is written to the field you define in $project or $addFields.

Output
=

Single combined string

Ready for display, export, or further string operations.

Conclusion

The $concat operator is an essential string tool in MongoDB aggregation pipelines. It lets you merge fields and literals into a single readable value — perfect for names, addresses, order labels, and report formatting.

For beginners, remember: include separators explicitly, guard null fields with $ifNull, and use $toString for numbers. For joining arrays, use $concatArrays instead.

💡 Best Practices

✅ Do

  • Include literal separators between field values
  • Wrap nullable fields with $ifNull
  • Use $toString before concatenating numbers
  • Keep separator literals consistent across pipelines
  • Use $trim after concat if spaces may trail

❌ Don’t

  • Confuse $concat with $concatArrays
  • Pass numbers directly without $toString
  • Forget that one null field nullifies the whole result
  • Assume MongoDB adds spaces between fields automatically
  • Concatenate very large strings without considering document size

Key Takeaways

Knowledge Unlocked

Five things to remember about $concat

Use these points when joining strings in MongoDB.

5
Core concepts
📝 02

Array Syntax

{ $concat: [a, b] }

Syntax
📏 03

Add Separators

Literals like " " or ", ".

Tip
04

Null = Null

Use $ifNull to guard.

Edge case
🔢 05

Numbers

Convert with $toString.

Types

❓ Frequently Asked Questions

$concat combines multiple string values into a single string. It accepts an array of expressions — field references, literals, or other string expressions.
The syntax is { $concat: [ <expression1>, <expression2>, ... ] }. You can include as many expressions as needed, including literal separators like a space or comma.
If any expression evaluates to null, $concat returns null for the entire result. Use $ifNull on individual fields to provide fallback empty strings.
$concat joins strings into one string. $concatArrays joins multiple arrays into one array. They operate on different data types.
$concat only works with strings. Convert numbers first using $toString, then pass the result to $concat.

Continue the Operator Series

Move on to $concatArrays for merging arrays, or review $arrayToObject for data transforms.

Next: $concatArrays →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful