Giới thiệu
Trong MongoDB, bạn có thể sử dụng con trỏ (cursor) để lặp qua các tài liệu trong một collection. Điều này rất hữu ích khi bạn cần xử lý từng tài liệu một cách riêng biệt hoặc thực hiện các thao tác phức tạp trên từng bản ghi.
Cú pháp cơ bản
var bienLuuTru;
var conTro = db.tenCollection.find();
while(conTro.hasNext()) {
bienLuuTru = conTro.next();
printjson(bienLuuTru);
};
Ví dụ minh họa
1. Tạo collection và thêm dữ liệu mẫu
> db.demoLapCollection.insertOne({"TenSinhVien":"John","TuoiSinhVien":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca81f2d6669774125247f") }
> db.demoLapCollection.insertOne({"TenSinhVien":"Larry","TuoiSinhVien":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8272d66697741252480") }
> db.demoLapCollection.insertOne({"TenSinhVien":"Chris","TuoiSinhVien":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8462d66697741252481") }
> db.demoLapCollection.insertOne({"TenSinhVien":"Robert","TuoiSinhVien":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ca8632d66697741252482") }
2. Hiển thị tất cả tài liệu với find()
> db.demoLapCollection.find().pretty();
Kết quả:
{ "_id" : ObjectId("5c9ca81f2d6669774125247f"), "TenSinhVien" : "John", "TuoiSinhVien" : 23 }
{ "_id" : ObjectId("5c9ca8272d66697741252480"), "TenSinhVien" : "Larry", "TuoiSinhVien" : 21 }
{ "_id" : ObjectId("5c9ca8462d66697741252481"), "TenSinhVien" : "Chris", "TuoiSinhVien" : 25 }
{ "_id" : ObjectId("5c9ca8632d66697741252482"), "TenSinhVien" : "Robert", "TuoiSinhVien" : 24 }
3. Lặp qua collection bằng cursor
> var tatCaTaiLieu;
> var tenCollection = db.demoLapCollection.find();
> while(tenCollection.hasNext()){
tatCaTaiLieu = tenCollection.next();
printjson(tatCaTaiLieu);
}
Kết quả sẽ hiển thị từng tài liệu một, giống như phương thức find() nhưng cho phép bạn xử lý logic tùy chỉnh cho mỗi tài liệu trong vòng lặp.
Khi nào nên sử dụng cursor?
- Cần xử lý logic phức tạp cho từng tài liệu
- Muốn tiết kiệm bộ nhớ khi xử lý dataset lớn (xử lý từng batch)
- Cần dừng lặp dựa trên điều kiện cụ thể