How can I concatenate an array of integer in MongoDB aggregation method?

To concatenate an array of integers in MongoDB aggregation, use the $reduce operator with $concat to combine array elements into a single string. Since integers must be converted to strings for concatenation, use $toString for type conversion.

Syntax

db.collection.aggregate([
    {
        $project: {
            concatenatedField: {
                $reduce: {
                    input: "$arrayField",
                    initialValue: "",
                    in: { $concat: ["$$value", "delimiter", { $toString: "$$this" }] }
                }
            }
        }
    }
])

Sample Data

db.demo377.insertOne({
    "ListOfIds": [1001, 1002, 1003, 1004, 1005, 1006, 1007]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5a73462ae06a1609a00b0e")
}

Example: Concatenate with Custom Delimiter

db.demo377.aggregate([
    {
        $project: {
            ListOfIds: {
                $let: {
                    vars: {
                        key: {
                            $reduce: {
                                input: "$ListOfIds",
                                initialValue: "",
                                in: { $concat: ["$$value", "++", { $toString: "$$this" }] }
                            }
                        }
                    },
                    in: { $substrCP: ["$$key", 2, { $strLenCP: "$$key" }] }
                }
            }
        }
    }
])
{ "_id": ObjectId("5e5a73462ae06a1609a00b0e"), "ListOfIds": "1001++1002++1003++1004++1005++1006++1007" }

How It Works

  • $reduce iterates through each array element
  • $toString converts integer values to strings for concatenation
  • $substrCP removes the initial delimiter from the beginning
  • $let creates variables for cleaner expression handling

Conclusion

Use $reduce with $concat and $toString to concatenate integer arrays in MongoDB aggregation. The $substrCP operator helps remove unwanted leading delimiters from the final result.

Updated on: 2026-03-15T02:44:06+05:30

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements