ใช้ findOne() ตรวจสอบความมีอยู่ของเอกสาร
เมธอด findOne() จะคืนค่าเอกสารแรกที่ตรงเงื่อนไข (หรือ null ถ้าไม่เจอ) เหมาะสำหรับตรวจสอบว่ามีข้อมูลอยู่หรือไม่ เร็วกว่า find().count() เพราะหยุดค้นหาที่เจอตัวแรก
รูปแบบคำสั่ง
db.yourCollectionName.findOne({ yourFieldName: 'yourValue' });
ตัวอย่างข้อมูล
> db.checkExistingDemo.insertOne({"StudentName":"John"});
> db.checkExistingDemo.insertOne({"StudentName":"Carol"});
> db.checkExistingDemo.insertOne({"StudentName":"Sam"});
> db.checkExistingDemo.insertOne({"StudentName":"Mike"});
คิวรี: ตรวจสอบว่ามี StudentName = "Carol" หรือไม่
> db.checkExistingDemo.findOne({StudentName: 'Carol'});
ผลลัพธ์
{ "_id" : ObjectId("5cbdf912ac184d684e3fa266"), "StudentName" : "Carol" }
การประยุกต์ใช้ในโค้ด
// ใน Mongo Shell / Script
var user = db.users.findOne({ email: "john@example.com" });
if (user) {
print("User exists: " + user._id);
} else {
print("User not found");
}
// ใน Application (Node.js driver)
const user = await db.collection('users').findOne({ email: 'john@example.com' });
if (user) { /* ... */ }
ประสิทธิภาพ
findOne()ใช้ Index ได้ (ถ้ามี Index บนฟิลด์ที่ค้นหา)- หยุดการค้นหาที่เจอตัวแรก - เร็วกว่า
count()หรือfind().toArray() - คืนค่า
nullไม่ใช่ Cursor - ใช้งานง่ายในเงื่อนไข If