Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีดึงชื่อฟิลด์ทั้งหมดในคอลเลกชัน 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 }

คิวรี่ Map Reduce สำหรับดึงชื่อฟิลด์ทั้งหมด:

> 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" ]