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 get array from a MongoDB collection?
To get an array from a MongoDB collection, you can use the aggregation framework with $unwind and $group operators to extract and collect array elements from nested documents.
Syntax
db.collection.aggregate([
{ "$unwind": "$arrayField" },
{ "$unwind": "$arrayField.nestedArray" },
{
"$group": {
"_id": null,
"resultArray": { "$push": "$arrayField.nestedArray.targetField" }
}
}
]);
Sample Data
db.getArrayDemo.insertOne({
"CustomerId": 101,
"CustomerDetails": [
{
"CustomerName": "Larry",
"CustomerFriendDetails": [
{ "CustomerFriendName": "Sam" },
{ "CustomerFriendName": "Robert" }
]
},
{
"CustomerName": "Chris",
"CustomerFriendDetails": [
{ "CustomerFriendName": "David" },
{ "CustomerFriendName": "Carol" }
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cda4949b50a6c6dd317adb7")
}
Display Collection Documents
db.getArrayDemo.find().pretty();
{
"_id": ObjectId("5cda4949b50a6c6dd317adb7"),
"CustomerId": 101,
"CustomerDetails": [
{
"CustomerName": "Larry",
"CustomerFriendDetails": [
{ "CustomerFriendName": "Sam" },
{ "CustomerFriendName": "Robert" }
]
},
{
"CustomerName": "Chris",
"CustomerFriendDetails": [
{ "CustomerFriendName": "David" },
{ "CustomerFriendName": "Carol" }
]
}
]
}
Extract Array from Nested Documents
db.getArrayDemo.aggregate([
{ "$unwind": "$CustomerDetails" },
{ "$unwind": "$CustomerDetails.CustomerFriendDetails" },
{
"$group": {
"_id": null,
"CustomerFriendDetails": { "$push": "$CustomerDetails.CustomerFriendDetails.CustomerFriendName" }
}
}
]);
{ "_id": null, "CustomerFriendDetails": [ "Sam", "Robert", "David", "Carol" ] }
How It Works
-
$unwinddeconstructs theCustomerDetailsarray into separate documents - Second
$unwindflattens the nestedCustomerFriendDetailsarrays -
$groupwith$pushcollects all friend names into a single array
Conclusion
Use MongoDB's aggregation pipeline with $unwind to flatten nested arrays and $group with $push to extract and collect specific array elements from complex document structures into a single result array.
Advertisements
