Concatenate fields in MongoDB?

To concatenate fields in MongoDB, use the $concat operator within an aggregation pipeline. This operator combines multiple string values into a single string, with optional separators between them.

Syntax

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

Sample Data

db.concatenateFieldsDemo.insertMany([
    {"StudentFirstName": "Adam", "StudentLastName": "Smith"},
    {"StudentFirstName": "John", "StudentLastName": "Doe"},
    {"StudentFirstName": "David", "StudentLastName": "Miller"},
    {"StudentFirstName": "Sam", "StudentLastName": "Williams"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd6ebf46d78f205348bc62e"),
        ObjectId("5cd6ebfc6d78f205348bc62f"),
        ObjectId("5cd6ec376d78f205348bc630"),
        ObjectId("5cd6ec436d78f205348bc631")
    ]
}

Example: Concatenate First and Last Names

Let's concatenate the first and last names with a "/" separator ?

db.concatenateFieldsDemo.aggregate([
    {
        $project: {
            "StudentFullName": {
                $concat: ["$StudentFirstName", "/", "$StudentLastName"]
            },
            "StudentFirstName": 1,
            "StudentLastName": 1
        }
    }
]);
{ "_id": ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName": "Adam", "StudentLastName": "Smith", "StudentFullName": "Adam/Smith" }
{ "_id": ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName": "John", "StudentLastName": "Doe", "StudentFullName": "John/Doe" }
{ "_id": ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName": "David", "StudentLastName": "Miller", "StudentFullName": "David/Miller" }
{ "_id": ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName": "Sam", "StudentLastName": "Williams", "StudentFullName": "Sam/Williams" }

Key Points

  • $concat only works with string values − non-string fields must be converted first using $toString.
  • Use $project to include original fields (value 1) along with the concatenated field.
  • Common separators include spaces " ", hyphens "-", or slashes "/".

Conclusion

The $concat operator in MongoDB aggregation pipelines effectively combines multiple string fields into one. Use it within $project to create new concatenated fields while preserving original data.

Updated on: 2026-03-15T01:18:07+05:30

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements