How do i get all keys in Mongodb collection?

learner picture learner · Jul 8, 2015 · Viewed 9.1k times · Source

I saw few solutions but those are not exact my solution. I have a DB with name results and collection name is marks like below:

db.marks.find();
{ "_id" : ObjectId("54f57522627af4bfdcf79764"), "name" : "John", "scroe1" : 23, "score2" : 21, "score5" : 12 }
{ "_id" : ObjectId("54f5761a627af4bfdcf79765"), "name" : "Mike", "scroe2" : 22, "score3" : 20, "score4" : 22 }
{ "_id" : ObjectId("559d0bc521cb2e056507c3e3"), "name" : "Bush", "score2" : 30 }

I tried with

var doc=db.marks.findOne(); for (var key in doc) print(key);

and i got

_id
name
score1
score2
score5

But i Want all keys in collection like below:

_id, name, score1, score2, score3, score4, score5

name scroe1 score2 score3here

Answer

Matthew Antolovich picture Matthew Antolovich · Jul 11, 2015

findOne will only return the first found document. Since the first document you list does not have the score3 and score4 keys, it will not display them. If you want to show all root-level keys across all documents, you would need to iterate through all the documents in the db.

var keys = [];
db.marks.find().forEach(function(doc){
    for (var key in doc){ 
        if(keys.indexOf(key) < 0){
           keys.push(key);
        }
    }
});

print(keys);