Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy xuất dữ liệu từ collection MongoDB với findOne()

Lấy một tài liệu đơn lẻ với findOne()

findOne() trả về duy nhất một document khớp filter (theo thứ tự tự nhiên hoặc sort). Hiệu quả hơn find().limit(1) cho trường hợp lấy 1 doc.

1. Dữ liệu mẫu

> 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" });

2. Tìm John Doe

> db.demo463.findOne({ "StudentName": "John Doe" });

3. Kết quả

{
    "_id": ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
    "StudentName": "John Doe",
    "StudentAge": 22,
    "StudentCountryName": "AUS"
}

findOne() vs find().limit(1)

Đặc điểmfindOne()find().limit(1)
Trả vềDocument (object) hoặc nullCursor (cần .next() hoặc toArray())
Hiệu suấtTối ưu nội bộ dừng sớmTương tự, nhưng overhead cursor
SortKhông hỗ trợ sort parameterHỗ trợ .sort() trước .limit()
ProjectionHỗ trợ param 2Hỗ trợ .project()

Ví dụ với projection

// Chỉ lấy tên và tuổi
db.demo463.findOne(
    { StudentName: "John Doe" },
    { projection: { _id: 0, StudentName: 1, StudentAge: 1 } }
);
// { "StudentName": "John Doe", "StudentAge": 22 }

findOneAndUpdate / findOneAndDelete / findOneAndReplace

Các biến thể atomic (nguyên tử) - tìm, sửa/xóa/thay thế VÀ trả về doc:

// Tìm, cập nhật, trả về doc SAU khi cập nhật (mặc định trả về TRƯỚC)
db.demo463.findOneAndUpdate(
    { StudentName: "John Doe" },
    { $set: { StudentAge: 23 } },
    { returnDocument: "after" }  // "before" | "after"
);

Lưu ý

  • Nếu không có document khớp → trả về null
  • Nếu nhiều document khớp → trả về document đầu tiên (theo natural order hoặc sort)
  • Luôn dùng projection để giảm network transfer