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ểm | findOne() | find().limit(1) |
|---|---|---|
| Trả về | Document (object) hoặc null | Cursor (cần .next() hoặc toArray()) |
| Hiệu suất | Tối ưu nội bộ dừng sớm | Tương tự, nhưng overhead cursor |
| Sort | Không hỗ trợ sort parameter | Hỗ trợ .sort() trước .limit() |
| Projection | Hỗ trợ param 2 | Hỗ 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