ใช้ findOne() สำหรับดึงข้อมูลเฉพาะเจาะจง
เมธอด findOne() คืนค่าเอกสารเดียวที่ตรงกับ query criteria เหมาะสำหรับ lookup ด้วย unique field หรือ primary key
ตัวอย่างข้อมูล
> db.demo473.insertOne({
"_id": new ObjectId(),
"Name": "Chris",
"details": { "X-Coordinate": 10, "Y-Coordinate": 15 }
});
> db.demo473.insertOne({
"_id": new ObjectId(),
"Name": "Bob",
"details": { "X-Coordinate": 11, "Y-Coordinate": 12 }
});
Query ดึงเอกสารที่ X-Coordinate = 11
> db.demo473.findOne({ 'details.X-Coordinate': 11 });
ผลลัพธ์
{ "_id": ObjectId(...), "Name": "Bob", "details": { "X-Coordinate": 11, "Y-Coordinate": 12 } }
Dot Notation สำหรับ Nested Field
details.X-Coordinate- เข้าถึงฟิลด์ใน subdocument- ทำงานได้ทั้ง find() และ findOne()
- รองรับความลึกไม่จำกัด:
a.b.c.d
Projection - ดึงเฉพาะฟิลด์ที่ต้องการ
// ดึงเฉพาะ Name และ Y-Coordinate
db.demo473.findOne(
{ 'details.X-Coordinate': 11 },
{ projection: { Name: 1, 'details.Y-Coordinate': 1, _id: 0 } }
);
// ผลลัพธ์: { "Name": "Bob", "details": { "Y-Coordinate": 12 } }
findOne() vs find().limit(1)
| ด้าน | findOne() | find().limit(1) |
|---|---|---|
| Return type | Document / null | Cursor |
| Performance | Optimized สำหรับ single doc | General cursor overhead |
| Usage | Direct assignment | ต้อง .next() หรือ toArray() |
กรณีไม่เจอข้อมูล
const result = db.demo473.findOne({ 'details.X-Coordinate': 999 });
if (result === null) {
print("ไม่พบข้อมูล");
} else {
print("พบ:", result.Name);
}