ใน MongoDB ไม่มีเมธอด findById() ให้ใช้ findOne() ร่วมกับเงื่อนไข _id เพื่อดึงเอกสารเดี่ยว สร้างคอลเลกชันตัวอย่าง:
> db.demo340.insertOne({_id:1,"Name":"Chris",Age:21});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo340.insertOne({_id:2,"Name":"David",Age:23});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo340.insertOne({_id:3,"Name":"Bob",Age:20});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo340.insertOne({_id:4,"Name":"Sam",Age:19});
{ "acknowledged" : true, "insertedId" : 4 }
แสดงข้อมูล:
> db.demo340.find();
ค้นหาเอกสาร _id = 1 ด้วย findOne():
> db.demo340.findOne({_id:1});
ผลลัพธ์:
{ "_id" : 1, "Name" : "Chris", "Age" : 21 }
ข้อแตกต่างระหว่าง find() และ findOne()
| คุณสมบัติ | find() | findOne() |
|---|---|---|
| คืนค่า | Cursor (ต้อง iterate) | Document เดียว (หรือ null) |
| ประสิทธิภาพ | เหมาะสำหรับหลายเอกสาร | หยุดค้นหาทันทีเมื่อเจอตัวแรก |
| การใช้งาน | ต้อง .next() หรือ toArray() | ใช้งานได้ทันที |
ใน Driver ต่างๆ (Node.js, Python, etc.)
ส่วนใหญ่มี helper method findById(id) ซึ่งเป็น wrapper ของ findOne({_id: id}) หากใช้ driver ตรงๆ ให้ใช้ findOne()