MongoDB query to concatenate values of array with other fields

To concatenate values of an array with other fields in MongoDB, use $reduce to convert the array into a single string, then $concat to combine it with other fields in the $project stage.

Syntax

db.collection.aggregate([
    {
        $project: {
            arrayAsString: {
                $reduce: {
                    input: "$arrayField",
                    initialValue: "",
                    in: { $concat: ["$$value", " ", "$$this"] }
                }
            },
            otherField: 1
        }
    },
    {
        $project: {
            result: { $concat: ["$otherField", "$arrayAsString"] }
        }
    }
])

Sample Data

db.demo359.insertOne({
    Name1: "Chris",
    Name2: "David",
    Subjects: ["MySQL", "MongoDB", "Java"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5694cdf8647eb59e5620d0")
}

Display the document to verify the structure ?

db.demo359.find().pretty();
{
    "_id": ObjectId("5e5694cdf8647eb59e5620d0"),
    "Name1": "Chris",
    "Name2": "David",
    "Subjects": [
        "MySQL",
        "MongoDB",
        "Java"
    ]
}

Example: Concatenate Array with Name Field

Concatenate the Name1 field with all Subjects array values ?

db.demo359.aggregate([
    {
        $project: {
            values: {
                $reduce: {
                    input: "$Subjects",
                    initialValue: "",
                    in: {
                        $concat: ["$$value", " ", "$$this"]
                    }
                }
            },
            Name1: 1
        }
    },
    {
        $project: {
            ConcatResult: { $concat: ["$Name1", "$values"] }
        }
    }
])
{ "_id": ObjectId("5e5694cdf8647eb59e5620d0"), "ConcatResult": "Chris MySQL MongoDB Java" }

How It Works

  • $reduce iterates through the array and builds a single concatenated string
  • initialValue: "" starts with an empty string
  • $$value is the accumulated result, $$this is the current array element
  • The second $project combines the string result with other fields using $concat

Conclusion

Use $reduce to convert arrays into concatenated strings, then $concat to combine with other fields. This approach handles arrays of any length and provides flexible string formatting options.

Updated on: 2026-03-15T02:37:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements