Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$reduceiterates through each array element -
$toStringconverts integer values to strings for concatenation -
$substrCPremoves the initial delimiter from the beginning -
$letcreates 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.
Advertisements
