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({
  "map":function() {
    for (var key in this) { emit(key, null); }
  "reduce":function(key, stuff) { return null; }, 
  "out":collection + "_keys"



No related content found.


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.