การดึงค่าเฉพาะฟิลด์เดียว (Field Value Only) ใน MongoDB
MongoDB find() คืนค่าเป็น Document เสมอ ถ้าต้องการแค่ค่าของฟิลด์เดียว (Scalar Value) ต้องใช้ forEach() loop รวมค่าเข้า Array หรือใช้ Aggregation $project กับ $map
ตัวอย่างการสร้างคอลเลกชันและเพิ่มข้อมูล
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Larry"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea537d628fa4220163b6e") }
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea53bd628fa4220163b6f") }
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea541d628fa4220163b70") }
> db.returnOnlyValueOfFieldDemo.insertOne({"ClientName":"Ramit"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ea549d628fa4220163b71") }
แสดงข้อมูลทั้งหมด
> db.returnOnlyValueOfFieldDemo.find().pretty();
ผลลัพธ์:
{ "_id" : ObjectId("5c9ea537d628fa4220163b6e"), "ClientName" : "Larry" }
{ "_id" : ObjectId("5c9ea53bd628fa4220163b6f"), "ClientName" : "Chris" }
{ "_id" : ObjectId("5c9ea541d628fa4220163b70"), "ClientName" : "Robert" }
{ "_id" : ObjectId("5c9ea549d628fa4220163b71"), "ClientName" : "Ramit" }
วิธีที่ 1: ใช้ forEach() Loop ใน Mongo Shell (สำหรับ Shell Script)
> var output = [];
> db.returnOnlyValueOfFieldDemo.find().forEach(function(document) {
output.push(document.ClientName);
});
// แสดงผล
> output;
[ "Larry", "Chris", "Robert", "Ramit" ]
วิธีที่ 2: ใช้ Aggregation $project + $map (MongoDB 3.6+)
> db.returnOnlyValueOfFieldDemo.aggregate([
{ $group: { _id: null, names: { $push: "$ClientName" } } },
{ $project: { _id: 0, names: 1 } }
]);
ผลลัพธ์:
{ "names" : [ "Larry", "Chris", "Robert", "Ramit" ] }
วิธีที่ 3: ใช้ distinct() (ถ้าต้องการค่า Unique เท่านั้น)
> db.returnOnlyValueOfFieldDemo.distinct("ClientName");
[ "Larry", "Chris", "Robert", "Ramit" ]
วิธีที่ 4: ใช้ map() บน Cursor (MongoDB 4.4+)
> db.returnOnlyValueOfFieldDemo.find().map(function(doc) { return doc.ClientName; });
[ "Larry", "Chris", "Robert", "Ramit" ]
การเปรียบเทียบวิธีต่างๆ
| วิธี | ใช้ได้ใน | ผลลัพธ์ | Unique Values | ประสิทธิภาพ |
|---|---|---|---|---|
| forEach + push | Mongo Shell | Array | ไม่ (มีซ้ำได้) | ดี |
| aggregate $push | ทุก Driver | Document + Array | ไม่ | ดี |
| distinct() | ทุก Driver | Array | ✅ ใช่ | ดี (มี Index) |
| cursor.map() | Mongo Shell 4.4+ | Array | ไม่ | ดี |
กรณีต้องการค่าเดี่ยว (Single Value)
// findOne() คืน Document
> var doc = db.collection.findOne({ _id: ObjectId("...") });
> doc.fieldName; // เข้าถึงค่าโดยตรง
// ใช้ projection ใน findOne
> db.collection.findOne({ _id: ... }, { projection: { fieldName: 1, _id: 0 } });
// คืน { "fieldName": "value" } ต้องเข้าถึง .fieldName
การใช้งานใน Application (Node.js Example)
// ดึง Array ของชื่อ
const names = await db.collection('demo')
.find({})
.project({ _id: 0, ClientName: 1 })
.map(doc => doc.ClientName)
.toArray();
// หรือ distinct
const uniqueNames = await db.collection('demo')
.distinct('ClientName');
เลือกวิธีตาม Use Case: distinct() สำหรับ Unique, aggregate $push สำหรับทุกค่า, forEach สำหรับ Shell Script