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
Working with MongoDB concatArrays in project on existing multi-array field
The $concatArrays operator is used to concatenate arrays and return the concatenated array. When working with multi-dimensional arrays, you can combine it with $reduce to flatten and concatenate nested arrays.
Syntax
{
"$project": {
"newFieldName": {
"$reduce": {
"input": "$arrayField",
"initialValue": [],
"in": { "$concatArrays": ["$$this", "$$value"] }
}
}
}
}
Sample Data
Let us create a collection with documents ?
db.demo338.insertOne({
"Name": "Chris",
"Marks1": [ [56,67,45], [67,89,90,91] ]
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5299baf8647eb59e56209f")
}
Display all documents from a collection with the help of find() method ?
db.demo338.find().pretty();
{
"_id" : ObjectId("5e5299baf8647eb59e56209f"),
"Name" : "Chris",
"Marks1" : [
[
56,
67,
45
],
[
67,
89,
90,
91
]
]
}
Example: Concatenating Multi-Array Field
Following is the query to work on the existing multi-array field and concatenate arrays ?
db.demo338.aggregate([
{ "$project": {
"Marks": {
"$reduce": {
"input": "$Marks1",
"initialValue": [],
"in": { "$concatArrays": ["$$value", "$$this"] }
}
}
}}
]);
{ "_id" : ObjectId("5e5299baf8647eb59e56209f"), "Marks" : [ 56, 67, 45, 67, 89, 90, 91 ] }
How It Works
-
$reduceiterates through each sub-array inMarks1 -
$$valueaccumulates the concatenated result (starts as empty array) -
$$thisrepresents the current sub-array being processed -
$concatArraysmerges the accumulator with the current sub-array
Conclusion
Use $concatArrays with $reduce to flatten multi-dimensional arrays in MongoDB. The $reduce operator iterates through nested arrays while $concatArrays concatenates them into a single flat array.
Advertisements
