Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีดึงข้อมูลจากคอลเลกชัน MongoDB


ใช้ 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, ExportLookup 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 ดีกว่า)