获取 MongoDB 集合中的所有字段名称?


你可以运用 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" ]

更新于: 30-Jul-2019

3 千次+ 浏览

开始你的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.