Me gustaría obtener los nombres de todas las claves de una colección de MongoDB.
Por ejemplo, de esta:
db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : [] } );
Me gustaría obtener las claves únicas:
type, egg, hello
Esto se puede hacer con 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"
})
A continuación, ejecute distinct en la colección resultante para encontrar todas las claves:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
Con Kristina's answer como inspiración, he creado una herramienta de código abierto llamada Variety que hace exactamente esto: https://github.com/variety/variety