我想获取 MongoDB 集合中所有键的名称。
例如,从这个:
db.things.insert( { type : ['dog', 'cat'] } );
db.things.insert( { egg : ['cat'] } );
db.things.insert( { type : [] } );
db.things.insert( { hello : [] } );
我想获取唯一键:
type, egg, hello
最佳答案
您可以使用 MapReduce 做到这一点:
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"
})
然后在结果集合上运行 distinct 以找到所有键:
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
https://stackoverflow.com/questions/2298870/
相关文章:
mongodb - NoSQL (MongoDB) vs Lucene (或 Solr) 作为你的数
mongodb - 向 MongoDB 集合中的每个文档添加新字段
node.js - 如何在 Node.js Web 应用程序中管理 MongoDB 连接?
mongodb - 如何在 MongoDB shell 中打印出 20 多个项目(文档)?
mongodb - 如何导出 MongoDB 中的所有集合?
node.js - Mongoose 中的 "__v"字段是什么
mongodb - 在 MongoDB 中实现数据版本控制的方法