ใช้ลูป while ร่วมกับ Cursor จาก find()
ไม่มีคำสั่งนับ cursor โดยตรง ต้องใช้ตรรกะกำหนดเองกับลูป while และ hasNext()
สร้างข้อมูลตัวอย่าง
> db.demo724.insertOne({ details: { id:101, otherDetails:[ {Name:"Chris"} ] } });
> db.demo724.insertOne({ });
> db.demo724.insertOne({ details: { id:1001 } });
แสดงข้อมูลทั้งหมด
> db.demo724.find();
ผลลัพธ์:
{ "_id" : ObjectId("5eab0cce43417811278f5890"), "details" : { "id" : 101, "otherDetails" : [ { "Name" : "Chris" } ] } }
{ "_id" : ObjectId("5eab0cce43417811278f5891") }
{ "_id" : ObjectId("5eab0cce43417811278f5892"), "details" : { "id" : 1001 } }
โค้ดนับจำนวนเอกสารที่มีฟิลด์ details
> var c=db.demo724.find();
> var detailsCount=0;
> while (c.hasNext()) {
var current = c.next();
if (typeof current["details"] != "undefined") {
detailsCount++;
}
}
> print("number of details: " + detailsCount);
ผลลัพธ์
number of details: 2