2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

MongoDB Get names of all keys in collection

I"d like to get the names of all the keys in a MongoDB collection.
For example, from this:
db.things.insert( { type : ["dog", "cat"] } );

db.things.insert( { egg : ["cat"] } );

db.things.insert( { type : [] } );

db.things.insert( { hello : []  } );

I"d like to get the unique keys:
type, egg, hello

userimage

You could do this with MapReduce:


mr = db.runCommand({ 

"mapreduce" : "my_collection", 

"map" : function() {   

for (var key in this)

{ emit(key, null); } 

}, 

"reduce" : function(key, stuff) { return null; },  

"out": "my_collection" + "_keys"

})

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id")["foo", "bar", "baz", "_id", ...]

Answer is