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 retrieve all nested fields from MongoDB collection?
To retrieve all nested fields from a MongoDB collection, use the $unwind aggregation operator to flatten arrays, then $project to extract specific nested fields into the document structure.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayFieldName" },
{ $project: {
"field1": "$arrayFieldName.nestedField1",
"field2": "$arrayFieldName.nestedField2"
}}
]);
Sample Data
db.demo138.insertMany([
{
"Id": 101,
"PlayerDetails": [
{"PlayerName": "Chris", "PlayerScore": 400},
{"PlayerName": "David", "PlayerScore": 1000}
]
},
{
"Id": 102,
"PlayerDetails": [
{"PlayerName": "Bob", "PlayerScore": 500},
{"PlayerName": "Carol", "PlayerScore": 600}
]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e31bb9ffdf09dd6d08539a1"),
"1": ObjectId("5e31bbcefdf09dd6d08539a2")
}
}
View Sample Data
db.demo138.find();
{
"_id": ObjectId("5e31bb9ffdf09dd6d08539a1"), "Id": 101, "PlayerDetails": [
{ "PlayerName": "Chris", "PlayerScore": 400 },
{ "PlayerName": "David", "PlayerScore": 1000 }
]
}
{
"_id": ObjectId("5e31bbcefdf09dd6d08539a2"), "Id": 102, "PlayerDetails": [
{ "PlayerName": "Bob", "PlayerScore": 500 },
{ "PlayerName": "Carol", "PlayerScore": 600 }
]
}
Retrieve All Nested Fields
db.demo138.aggregate([
{ $unwind: "$PlayerDetails" },
{ $project: {
"PlayerName": "$PlayerDetails.PlayerName",
"PlayerScore": "$PlayerDetails.PlayerScore"
}}
]);
{ "_id": ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName": "Chris", "PlayerScore": 400 }
{ "_id": ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName": "David", "PlayerScore": 1000 }
{ "_id": ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName": "Bob", "PlayerScore": 500 }
{ "_id": ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName": "Carol", "PlayerScore": 600 }
How It Works
-
$unwindcreates separate documents for each array element -
$projectextracts nested fields to the top level of each document - Each nested object becomes an individual document with the specified fields
Conclusion
Use $unwind followed by $project in aggregation pipelines to flatten nested arrays and extract specific fields. This transforms nested data structures into individual documents for easier querying and analysis.
Advertisements
