Sử dụng forEach() trên cursor để duyệt và hiển thị document. Tham số callback nhận 2 đối số: document hiện tại và undefined (trong một số phiên bản shell).
Tạo collection
> db.demo496.insertOne({"Name":"David","CountryName":"US"});
> db.demo496.insertOne({"Name":"John","CountryName":"AUS"});
> db.demo496.insertOne({"Name":"Robert","CountryName":"UK"});
Hiển thị bình thường
> db.demo496.find();
Kết quả: 3 document đầy đủ
forEach với callback (done, notDone) => in notDone
> db.demo496.find({}).forEach((done, notDone) => { printjson(notDone); });
Kết quả:
undefined undefined undefined
forEach in done (document thực tế)
> db.demo496.find({}).forEach((done, notDone) => { printjson(done); });
Kết quả:
{
"_id": ObjectId("5e84b04ab0f3fa88e22790ce"),
"Name": "David", "CountryName": "US"
}
{
"_id": ObjectId("5e84b054b0f3fa88e22790cf"),
"Name": "John", "CountryName": "AUS"
}
{
"_id": ObjectId("5e84b05db0f3fa88e22790d0"),
"Name": "Robert", "CountryName": "UK"
}
Giải thích:
forEach(callback)duyệt cursor, gọi callback cho mỗi document- Callback signature:
function(document, index)- tham số 2 là index (0-based), không phải "notDone" - Ví dụ gốc nhầm lẫn tham số:
notDonethực ra là index (0,1,2) nhưng in ra undefined doprintjsontrên number có thể hiển thị khác - Cách đúng:
forEach(doc => printjson(doc))hoặcforEach((doc, idx) => ...)
Cách in đẹp hơn:
> db.demo496.find().forEach(printjson) // Hoặc > db.demo496.find().forEach(doc => print(tojson(doc)))
forEach hữu ích khi cần logic phức tạp cho mỗi document (gửi email, gọi API, tính toán...) thay vì chỉ hiển thị.