【发布时间】:2011-03-01 03:12:08
【问题描述】:
更新: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 sn-p,我们会得到:
[ "_id", "egg", "foo", "hello", "type" ]
但是我们不会得到嵌套在数据结构中的 bar 和 baaar 键。问题是:我如何检索所有键,无论它们的深度如何?理想情况下,我实际上希望脚本深入到所有深度,产生如下输出:
["_id","egg","foo","foo.bar","foo.bar.baaar","hello","type"]
提前谢谢你!
【问题讨论】: