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