Get names of all keys in the MongoDB collection?

Since MongoDB documents can have different structures (no fixed schema), getting all key names requires iterating over documents. There are multiple approaches depending on whether you need keys from one document or all documents.

Method 1: Using JavaScript Loop (Single Document)

Use findOne() to get a document and loop through its keys ?

var doc = db.studentGetKeysDemo.findOne();
for (var key in doc) {
    print(key);
}

Sample Data

db.studentGetKeysDemo.insertOne({
    "StudentId": 1,
    "StudentName": "Larry",
    "StudentAge": 23,
    "StudentAddress": "US",
    "StudentHobby": ["Cricket", "Football", "Reading Novel"],
    "StudentMathMarks": 89,
    "StudentDOB": ISODate("1998-04-06")
});

The output is ?

_id
StudentId
StudentName
StudentAge
StudentAddress
StudentHobby
StudentMathMarks
StudentDOB

Limitation: This only returns keys from one document. If different documents have different fields, some keys may be missed.

Method 2: Using MapReduce (All Documents)

To get all unique keys across the entire collection ?

db.studentGetKeysDemo.mapReduce(
    function() {
        for (var key in this) { emit(key, null); }
    },
    function(key, values) { return null; },
    { out: "allKeys" }
);

db.allKeys.distinct("_id");
["_id", "StudentId", "StudentName", "StudentAge", "StudentAddress", "StudentHobby", "StudentMathMarks", "StudentDOB"]

Method 3: Using $objectToArray (MongoDB 3.6+)

The most efficient approach using aggregation ?

db.studentGetKeysDemo.aggregate([
    { $project: { keys: { $objectToArray: "$$ROOT" } } },
    { $unwind: "$keys" },
    { $group: { _id: null, allKeys: { $addToSet: "$keys.k" } } }
]);
{ "_id": null, "allKeys": ["_id", "StudentId", "StudentName", "StudentAge", "StudentAddress", "StudentHobby", "StudentMathMarks", "StudentDOB"] }

Conclusion

Use the JavaScript loop for quick single-document inspection. For all unique keys across the entire collection, use the $objectToArray aggregation approach (MongoDB 3.6+) which is the most efficient and recommended method.

Updated on: 2026-03-14T23:16:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements