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 to append to array in MongoDB?
To append to array in MongoDB, use the $concatArrays operator in aggregation pipelines to combine multiple arrays into a single array. This operator concatenates arrays and returns the combined result.
Syntax
db.collection.aggregate([
{
$project: {
newField: {
$concatArrays: ["$array1", "$array2", ...]
}
}
}
])
Sample Data
db.demo435.insertMany([
{"FirstName": ["Chris"], "LastName": ["Brown"]},
{"FirstName": ["David"], "LastName": ["Miller"]},
{"FirstName": ["John"], "LastName": ["Doe"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e7719b1bbc41e36cc3cae97"),
ObjectId("5e7719bdbbc41e36cc3cae98"),
ObjectId("5e7719c6bbc41e36cc3cae99")
]
}
Display Sample Data
db.demo435.find().pretty();
{
"_id": ObjectId("5e7719b1bbc41e36cc3cae97"),
"FirstName": ["Chris"],
"LastName": ["Brown"]
}
{
"_id": ObjectId("5e7719bdbbc41e36cc3cae98"),
"FirstName": ["David"],
"LastName": ["Miller"]
}
{
"_id": ObjectId("5e7719c6bbc41e36cc3cae99"),
"FirstName": ["John"],
"LastName": ["Doe"]
}
Example: Concatenate FirstName and LastName Arrays
Append the LastName array to the FirstName array to create a combined FullName array ?
db.demo435.aggregate([
{
$project: {
FullName: {
$concatArrays: ["$FirstName", "$LastName"]
}
}
}
]);
{"_id": ObjectId("5e7719b1bbc41e36cc3cae97"), "FullName": ["Chris", "Brown"]}
{"_id": ObjectId("5e7719bdbbc41e36cc3cae98"), "FullName": ["David", "Miller"]}
{"_id": ObjectId("5e7719c6bbc41e36cc3cae99"), "FullName": ["John", "Doe"]}
Key Points
-
$concatArraysworks only in aggregation pipelines, not in update operations. - The operator preserves the order of elements from left to right.
- If any input array is null, the result will be null.
Conclusion
The $concatArrays operator efficiently combines multiple arrays into one during aggregation. It maintains element order and is ideal for creating composite arrays from existing array fields.
Advertisements
