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 display only the keys from nested MongoDB documents?
To display only the keys from nested MongoDB documents, use the aggregation pipeline with $reduce, $map, and $objectToArray operators to extract and combine all field names from nested objects or arrays.
Syntax
db.collection.aggregate([
{
$project: {
keys: {
$reduce: {
input: "$arrayField",
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$map: {
input: { $objectToArray: "$$this" },
in: "$$this.k"
}
}
]
}
}
}
}
}
]);
Sample Data
db.demo740.insertOne({
"details": [
{
"Name": "Chris",
"Age": 21,
"CountryName": "US"
},
{
"Name": "Bob",
"Age": 20,
"CountryName": "UK",
"isMarried": true
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ead700c57bb72a10bcf066d")
}
Example: Extract Keys from Nested Documents
db.demo740.aggregate([
{
$project: {
ListKeys: {
$reduce: {
input: "$details",
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$map: {
input: {
$objectToArray: "$$this"
},
in: "$$this.k"
}
}
]
}
}
}
}
}
]);
{
"_id": ObjectId("5ead700c57bb72a10bcf066d"),
"ListKeys": [
"Name",
"Age",
"CountryName",
"Name",
"Age",
"CountryName",
"isMarried"
]
}
How It Works
-
$objectToArrayconverts each nested document to key-value pairs -
$mapextracts only the keys ("k" field) from each pair -
$reduceiterates through the array and concatenates all keys -
$concatArrayscombines keys from all nested documents
Conclusion
Use MongoDB's aggregation pipeline with $reduce and $objectToArray to extract all field names from nested documents. This approach works with arrays containing multiple nested objects with varying structures.
Advertisements
