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
Extract all the values and display in a single line with MongoDB
To extract all values from nested arrays and display them in a single line in MongoDB, use the $unwind operator to flatten arrays and $group with $push to combine all values into one array.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $unwind: "$arrayField.nestedArray" },
{ $group: { _id: null, result: { $push: "$arrayField.nestedArray" } } }
]);
Sample Data
db.demo389.insertOne({
"details": [
{ "Name": ["Chris", "David"] },
{ "Name": ["Bob", "Mike"] },
{ "Name": ["Carol", "Sam"] },
{ "Name": ["David", "John"] }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5d1d8f22064be7ab44e7f9")
}
View Sample Data
db.demo389.find();
{
"_id": ObjectId("5e5d1d8f22064be7ab44e7f9"),
"details": [
{ "Name": ["Chris", "David"] },
{ "Name": ["Bob", "Mike"] },
{ "Name": ["Carol", "Sam"] },
{ "Name": ["David", "John"] }
]
}
Extract All Values
db.demo389.aggregate([
{ $unwind: "$details" },
{ $unwind: "$details.Name" },
{ $project: {
"_id": "$_id",
"Name": "$details.Name"
}},
{ $group: {
_id: "_id",
out: { $push: "$Name" }
}},
{ $project: {
"_id": 0,
"NameArray": "$out"
}}
]);
{ "NameArray": ["Chris", "David", "Bob", "Mike", "Carol", "Sam", "David", "John"] }
How It Works
-
First $unwind: Flattens the
detailsarray into separate documents -
Second $unwind: Flattens each
Namearray to individual string values -
$group: Combines all individual names back into a single array using
$push - $project: Formats the final output with a clean field name
Conclusion
Use double $unwind operations followed by $group with $push to extract all values from nested arrays and combine them into a single array. This aggregation pipeline effectively flattens complex nested structures.
Advertisements
