Bốn thao tác CRUD cơ bản trên một collection:
- findOne: lấy đúng một document khớp điều kiện (hoặc null).
- find: trả về một cursor (con trỏ) tới nhiều document khớp.
- insertOne: thêm một document mới.
- updateOne: cập nhật document đầu tiên khớp filter.
Ví dụ:
await users.insertOne({ email: "a@example.com", name: "Ada" })
await users.updateOne({ email: "a@example.com" }, { $set: { name: "Ada Lovelace" } })
const user = await users.findOne({ email: "a@example.com" })Lưu ý: luôn biết filter của mình có dùng index không.
Nếu không, MongoDB phải quét cả collection (collection scan) và sẽ rất chậm khi dữ liệu lớn.
Four basic CRUD operations on a collection:
- findOne: returns exactly one matching document (or null).
- find: returns a cursor (a pointer) to many matching documents.
- insertOne: inserts a new document.
- updateOne: updates the first document matching the filter.
Example:
await users.insertOne({ email: "a@example.com", name: "Ada" })
await users.updateOne({ email: "a@example.com" }, { $set: { name: "Ada Lovelace" } })
const user = await users.findOne({ email: "a@example.com" })Note: always know whether your filter uses an index.
If not, MongoDB must scan the whole collection (collection scan), which gets very slow as data grows.