更新:MongoDB的后续操作获取集合中所有键的名称.
正如Kristina所指出的,可以使用Mongodb的map/reduce来列出集合中的键:
db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] });
db.things.insert( { hello : [] } );
mr = db.runCommand({"mapreduce" : "things",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) {
return null;
}})
db[mr.result].distinct("_id")
//output: [ "_id", "egg", "hello", "type" ]
Run Code Online (Sandbox Code Playgroud)
只要我们想要只获得位于第一级深度的键,这就可以了.但是,它将无法检索位于更深层次的密钥.如果我们添加一条新记录:
db.things.insert({foo: {bar: {baaar: true}}})
Run Code Online (Sandbox Code Playgroud)
我们再次运行上面的map-reduce + distinct片段,我们将得到:
[ …Run Code Online (Sandbox Code Playgroud)