コレクション内のすべてのキーの名前を取得する

MongoDBのコレクションにあるすべてのキーの名前を取得したいのですが。

例えば、この中から

db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : []  } );

ユニークキーを取得したいと思います。

type, egg, hello
ソリューション

これを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"
})

そして、結果のコレクションに対して distinct を実行して、すべてのキーを見つけます。

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

Kristina's answer]1にヒントを得て、Varietyというオープンソースのツールを作りました。これはまさにこれを行うものです。https://github.com/variety/variety

解説 (2)

これを試してみてください。

doc=db.thinks.findOne();
for (key in doc) print(key);
解説 (8)