ใช้ findOne() สำหรับดึงเอกสารเดี่ยว
เมธอด findOne() คืนค่าเอกสารแรกที่ตรงกับเงื่อนไข (หรือเอกสารแรกในคอลเลกชันถ้าไม่ระบุ filter)
ตัวอย่างข้อมูล
> db.demo463.insertOne({ "StudentName": "Chris Brown", "StudentAge": 21, "StudentCountryName": "US" });
> db.demo463.insertOne({ "StudentName": "David Miller", "StudentAge": 23, "StudentCountryName": "UK" });
> db.demo463.insertOne({ "StudentName": "John Doe", "StudentAge": 22, "StudentCountryName": "AUS" });
> db.demo463.insertOne({ "StudentName": "John Smith", "StudentAge": 24, "StudentCountryName": "US" });
Query ดึงข้อมูล John Doe
> db.demo463.findOne({ "StudentName": "John Doe" });
ผลลัพธ์
{ "_id": ObjectId(...), "StudentName": "John Doe", "StudentAge": 22, "StudentCountryName": "AUS" }
find() vs findOne()
| คุณสมบัติ | find() | findOne() |
|---|---|---|
| คืนค่า | Cursor (ต้อง iterate) | Document เดียว (หรือ null) |
| ประสิทธิภาพ | เหมาะสำหรับหลายเอกสาร | หยุดค้นหาเมื่อเจอตัวแรก |
| การใช้งาน | Report, List, Export | Lookup by ID, Check exists, Get single |
ตัวเลือกการ Project ฟิลด์
// ดึงเฉพาะบางฟิลด์
db.demo463.findOne({ "StudentName": "John Doe" }, { projection: { StudentAge: 1, StudentCountryName: 1 } });
// ไม่รวม _id
db.demo463.findOne({ "StudentName": "John Doe" }, { projection: { _id: 0 } });
Best Practices
- ใช้ findOne() เมื่อคาดหวังผลลัพธ์ 0-1 รายการ
- สร้าง index บนฟิลด์ที่ query บ่อย
- ระบุ projection เพื่อลด network transfer
- หลีกเลี่ยง find().limit(1) แทน findOne() (findOne() optimize ดีกว่า)