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

  • $objectToArray converts each nested document to key-value pairs
  • $map extracts only the keys ("k" field) from each pair
  • $reduce iterates through the array and concatenates all keys
  • $concatArrays combines 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.

Updated on: 2026-03-15T03:53:53+05:30

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements