Select distinct for MongoDB
Here is a handy script I’ve been using for MongoDB to retrieve a list of all the fields used in a collection. This uses a map/reduce routine and has to comb over all the documents in a collection so you may want to exercise caution when using this script.
// usage:
// mongo localhost/foo --quiet --eval="var collection='bar';" getcollectionkeys.js
var mr = db.runCommand({
"mapreduce":collection,
"map":function() {
for (var key in this) { emit(key, null); }
},
"reduce":function(key, stuff) { return null; },
"out":collection + "_keys"
})
print(db[mr.result].distinct("_id"))
db[collection+"_keys"].drop()