ใช้ Projection ใน find()
ระบุฟิลด์ที่ต้องการในพารามิเตอร์ที่ 2 ของ find() โดยตั้งค่า 1 (รวม) หรือ 0 (ยกเว้น)
ไวยากรณ์
db.yourCollectionName.find({}, {"yourFieldName": 1}).pretty();
ตัวอย่าง
สร้างคอลเลกชัน retrieveValueFromAKeyDemo:
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"});
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"});
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"});
ดึงเฉพาะ CustomerCountryName
> db.retrieveValueFromAKeyDemo.find({}, {"CustomerCountryName": 1}).pretty();
ผลลัพธ์ (ยังมี _id):
{ "_id" : ObjectId("..."), "CustomerCountryName" : "US" }
{ "_id" : ObjectId("..."), "CustomerCountryName" : "AUS" }
{ "_id" : ObjectId("..."), "CustomerCountryName" : "UK" }
ไม่อยากได้ _id
> db.retrieveValueFromAKeyDemo.find({}, {_id: 0, "CustomerCountryName": 1}).pretty();
ผลลัพธ์:
{ "CustomerCountryName" : "US" }
{ "CustomerCountryName" : "AUS" }
{ "CustomerCountryName" : "UK" }
สามารถระบุหลายฟิลด์ได้ เช่น {_id:0, "CustomerName":1, "CustomerAge":1}