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
Make an array of multiple arrays in MongoDB?
To make an array of multiple arrays in MongoDB, use $unwind in the aggregation pipeline to deconstruct array fields. This operation creates separate documents for each array element, effectively flattening multiple arrays into individual elements.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" }
]);
Sample Data
db.demo289.insertMany([
{"Section": ["A", "B", "E"], "Name": "Chris"},
{"Section": ["C", "D", "B"], "Name": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4c06fcf49383b52759cbc3"),
ObjectId("5e4c070af49383b52759cbc4")
]
}
View Sample Data
db.demo289.find();
{
"_id": ObjectId("5e4c06fcf49383b52759cbc3"),
"Section": ["A", "B", "E"],
"Name": "Chris"
}
{
"_id": ObjectId("5e4c070af49383b52759cbc4"),
"Section": ["C", "D", "B"],
"Name": "David"
}
Example: Unwind Array Elements
Use $unwind to deconstruct the Section arrays into separate documents ?
db.demo289.aggregate([
{ $unwind: "$Section" }
]);
{"_id": ObjectId("5e4c06fcf49383b52759cbc3"), "Section": "A", "Name": "Chris"}
{"_id": ObjectId("5e4c06fcf49383b52759cbc3"), "Section": "B", "Name": "Chris"}
{"_id": ObjectId("5e4c06fcf49383b52759cbc3"), "Section": "E", "Name": "Chris"}
{"_id": ObjectId("5e4c070af49383b52759cbc4"), "Section": "C", "Name": "David"}
{"_id": ObjectId("5e4c070af49383b52759cbc4"), "Section": "D", "Name": "David"}
{"_id": ObjectId("5e4c070af49383b52759cbc4"), "Section": "B", "Name": "David"}
How It Works
The $unwind operator creates a new document for each element in the specified array field. Each resulting document contains the original document's fields with the array field replaced by a single array element.
Conclusion
Use $unwind in MongoDB aggregation to deconstruct arrays into individual documents. This effectively flattens multiple arrays, creating separate documents for each array element while preserving other document fields.
