$concatArrays (Concatenate Arrays)
Last updated: 2026-10-09
$concatArrays (Concatenate Arrays)
$concatArrays merges two or more arrays into a single new array. It is commonly used to combine tag lists, history records, or paged data. Every argument must resolve to an array; if any argument is null or missing the whole result is null. It never mutates the source arrays, returning a fresh merged array, which makes it ideal for composing fields inside $addFields or $project. Unlike $concat, which only joins strings, $concatArrays works exclusively with arrays.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $concatArrays: [ <array1>, <array2>, ... ] }
⚙️ Parameters
| array | Array expressions to merge; at least two. |
|---|
Returns:A new merged array; null if any argument is null or missing
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $concatArrays: merge tags and aliases
db.products.aggregate([
{ $project: {
allTags: { $concatArrays: ['$tags', '$aliases'] }
} }
])
Output:
{ '_id': 1, 'allTags': [ 'a', 'b', 'c', 'd' ] }
📌 Notes
- All arguments must be arrays; split strings with $split first or join them with $concat
- Any null argument makes the whole result null; guard with $ifNull
- Returns a new array and never touches the source document
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan $concatArrays join strings?
ANo, it only accepts arrays. Join strings with $concat, or split them into arrays first.
QWhat happens if an argument is null?
AThe whole result becomes null. Replace null with an empty array via $ifNull.
QHow is $concatArrays different from $push?
A$push accumulates elements in $group, while $concatArrays merges existing arrays inside an expression.