ใช้ $project ร่วม $cond, $isArray, $size เพื่อนับจำนวนสมาชิกในอาร์เรย์ของแต่ละเอกสาร สร้างคอลเลกชันตัวอย่าง:
> db.demo332.insertOne({details:[{Name:"Chris",Age:21}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e521f16f8647eb59e56208e") }
> db.demo332.insertOne({details:[{Name:"David",Age:23},{Name:"Bob",Age:22}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e521f21f8647eb59e56208f") }
แสดงข้อมูล:
> db.demo332.find();
คิวรีนับจำนวนสมาชิกในอาร์เรย์ details:
> db.demo332.aggregate([
{ $project: {
numberOfDocuments: { $cond: { if: { $isArray: "$details" }, then: { $size: "$details" }, else: "No Documents" } }
}}
])
ผลลัพธ์:
{ "_id" : ObjectId("5e521f16f8647eb59e56208e"), "numberOfDocuments" : 1 }
{ "_id" : ObjectId("5e521f21f8647eb59e56208f"), "numberOfDocuments" : 2 }
คำอธิบายโอเปอเรเตอร์
$isArray: ตรวจสอบว่าค่าเป็นอาร์เรย์หรือไม่$size: นับจำนวนสมาชิกในอาร์เรย์ (ใช้ได้เฉพาะใน $project)$cond: if-then-else (ternary operator)- หากไม่ใช่อาร์เรย์ คืนค่า "No Documents" (string)
วิธีอื่น
{$project: {count: {$size: "$details"}}}- error หาก details ไม่ใช่ array- MongoDB 4.4+:
{$size: { $ifNull: ["$details", []] }}ป้องกัน error - นับทั้งคอลเลกชัน:
db.collection.countDocuments()หรือaggregate([{$count: "total"}])