Update:次随访至MongoDB Get names of all keys in collection次.
正如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" ]
只要我们只想得到位于第一层深度的关键点,这就行了.然而,它将无法检索位于更深层次的密钥.如果我们添加新记录:
db.things.insert({foo: {bar: {baaar: true}}})
我们再次运行上面的map reduce+distinct片段,我们将得到:
[ "_id", "egg", "foo", "hello", "type" ]
但我们不会得到嵌套在数据 struct 中的bar和baaar键.问题是:如何检索所有键,无论其深度如何?理想情况下,我希望脚本能够深入到各个层次,产生如下输出:
["_id","egg","foo","foo.bar","foo.bar.baaar","hello","type"]
提前谢谢!