更新: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) 有没有办法在mongo的shell中找出文档中的字段/键?举个例子,假设我们有一个类似(伪代码)的文档:
{
"message": "Hello, world",
"from": "hal",
"field": 123
}
Run Code Online (Sandbox Code Playgroud)
我想在shell中运行一个命令,返回该文档中的字段/键列表.例如,像这样:
> var message = db.messages.findOne()
> message.keys()
... prints out "message, from, field"
Run Code Online (Sandbox Code Playgroud)
谢谢!