獲取 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" ]
廣告