Concatenate strings from two fields into a third field in MongoDB?

To concatenate strings from two fields into a third field in MongoDB, use the $concat operator within an aggregation pipeline with $project stage.

Syntax

db.collection.aggregate([
    { $project: { "newFieldName": { $concat: [ "$field1", "delimiter", "$field2" ] } } }
]);

Sample Data

db.concatenateStringsDemo.insertMany([
    {"StudentFirstName": "John", "StudentLastName": "Doe"},
    {"StudentFirstName": "John", "StudentLastName": "Smith"},
    {"StudentFirstName": "Carol", "StudentLastName": "Taylor"},
    {"StudentFirstName": "David", "StudentLastName": "Miller"},
    {"StudentFirstName": "James", "StudentLastName": "Williams"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9bb7362d66697741252444"),
        ObjectId("5c9bb7402d66697741252445"),
        ObjectId("5c9bb74c2d66697741252446"),
        ObjectId("5c9bb7752d66697741252447"),
        ObjectId("5c9bb7862d66697741252448")
    ]
}

Example: Creating Full Name Field

Let's concatenate "StudentFirstName" and "StudentLastName" into a "StudentFullName" field ?

db.concatenateStringsDemo.aggregate([
    { $project: { "StudentFullName": { $concat: [ "$StudentFirstName", " / ", "$StudentLastName" ] } } }
]);
{ "_id": ObjectId("5c9bb7362d66697741252444"), "StudentFullName": "John / Doe" }
{ "_id": ObjectId("5c9bb7402d66697741252445"), "StudentFullName": "John / Smith" }
{ "_id": ObjectId("5c9bb74c2d66697741252446"), "StudentFullName": "Carol / Taylor" }
{ "_id": ObjectId("5c9bb7752d66697741252447"), "StudentFullName": "David / Miller" }
{ "_id": ObjectId("5c9bb7862d66697741252448"), "StudentFullName": "James / Williams" }

Including Original Fields

To keep the original fields along with the concatenated field ?

db.concatenateStringsDemo.aggregate([
    { $project: { 
        "StudentFirstName": 1,
        "StudentLastName": 1,
        "StudentFullName": { $concat: [ "$StudentFirstName", " ", "$StudentLastName" ] }
    }}
]);

Key Points

  • The $concat operator takes an array of strings to concatenate
  • Field references use $ prefix: "$fieldName"
  • Add delimiters like spaces or symbols between fields for readability
  • Use fieldName: 1 in $project to include original fields in output

Conclusion

The $concat operator in MongoDB aggregation pipelines efficiently combines multiple string fields into a single field with custom delimiters, making it ideal for creating computed fields like full names or formatted addresses.

Updated on: 2026-03-15T00:32:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements