ใช้คำสั่ง distinct() เพื่อดึงค่าที่ไม่ซ้ำกันจากฟิลด์อาร์เรย์ แล้วใช้ .length นับจำนวน
ตัวอย่างข้อมูลทดสอบ
> db.demo36.insertOne({"Names":["Chris","Bob"]});
> db.demo36.insertOne({"Names":["Mike","Sam","Carol"]});
> db.demo36.insertOne({"Names":["Chris","Bob","David"]});
แสดงข้อมูลทั้งหมด
> db.demo36.find();
{
"_id" : ObjectId("5e17643bcfb11e5c34d898d4"),
"Names" : [ "Chris", "Bob" ]
}
{
"_id" : ObjectId("5e176449cfb11e5c34d898d5"),
"Names" : [ "Mike", "Sam", "Carol" ]
}
{
"_id" : ObjectId("5e17645bcfb11e5c34d898d6"),
"Names" : [ "Chris", "Bob", "David" ]
}
คำสั่งหาจำนวนค่า Distinct
> db.demo36.distinct('Names').length;
ผลลัพธ์
6
คำอธิบาย: ค่าที่ไม่ซ้ำกันคือ Chris, Bob, Mike, Sam, Carol, David รวม 6 ค่า (Chris และ Bob ซ้ำในเอกสารที่ 1 และ 3 นับแค่ครั้งเดียว)