คุณสามารถใช้แนวคิดของ 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" ]