获取 MongoDB 集合中的所有字段名称?
mongodbdatabasebig data analytics更新于 2026/1/13 6:07:17
您可以使用 Map Reduce 的概念。首先,我们创建一个包含文档的集合 −
> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90")
}
以下是使用 find() 方法显示集合中的所有文档的查询 −
> db.getAllFieldNamesDemo.find();
这将产生以下输出 −
{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }
以下是获取 MongoDB 集合中所有字段名称的查询 −
> myMapReduce = db.runCommand({
"mapreduce" : "getAllFieldNamesDemo",
"map" : function() {
for (var myKey in this) { emit(myKey, null); }
},
"reduce" : function(myKey, s) { return null; },
"out": "getAllFieldNamesDemo" + "_k"
})
{
"result" : "getAllFieldNamesDemo_k",
"timeMillis" : 1375,
"counts" : {
"input" : 1,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1
}
> db[myMapReduce.result].distinct("_id");
这将产生以下输出,显示字段名称 −
[ "StudentAge", "StudentFirstName", "_id" ]

