Ich möchte die Namen aller Schlüssel in einer MongoDB-Auflistung zu erhalten.
Zum Beispiel von diesem:
db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : [] } );
Ich würde gerne die eindeutigen Schlüssel erhalten:
type, egg, hello
Sie könnten dies mit MapReduce tun:
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"
})
Führen Sie dann distinct auf der resultierenden Sammlung aus, um alle Schlüssel zu finden:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
Mit Kristinas Antwort als Inspiration habe ich ein Open-Source-Tool namens Variety entwickelt, das genau das tut: https://github.com/variety/variety
Versuchen Sie dies:
doc=db.thinks.findOne();
for (key in doc) print(key);