Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ดึงค่าทั้งหมดของ Field ใน MongoDB ด้วย distinct()

ใช้ distinct() ดึงค่า Unique ของ Field แบบ Array

db.yourCollectionName.distinct("yourFieldName");

สร้างข้อมูลตัวอย่าง (Field เป็น Array)

> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc89ed3c9d04998abf011") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,60]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8abd3c9d04998abf012") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8d7d3c9d04998abf013") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,70]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8e2d3c9d04998abf014") }

ดึงค่า Unique ทั้งหมดจาก Array Field

> db.listAllValuesOfCeratinFieldsDemo.distinct("ListOfValues");
[ 10, 20, 30, 40, 50, 60, 70 ]

distinct() จะ Flatten Array และคืนค่าที่ไม่ซ้ำกันทั้งหมด