ใช้เมธอด distinct() เพื่อดึงค่าที่ไม่ซ้ำกันจากฟิลด์อาร์เรย์ทั่วทั้งคอลเลกชัน
รูปแบบคำสั่ง
db.collectionName.distinct("arrayFieldName");
ตัวอย่างเต็มรูปแบบ
1. สร้างข้อมูลตัวอย่าง
> db.distinctAggregation.insertOne({"UserName":"Larry","UserPost":["Hi","Hello"]});
> db.distinctAggregation.insertOne({"UserName":"Chris","UserPost":["Hi","Good Morning"]});
> db.distinctAggregation.insertOne({"UserName":"Robert","UserPost":["Awesome"]});
2. แสดงข้อมูลทั้งหมด
> db.distinctAggregation.find().pretty();
{ "_id" : ObjectId("..."), "UserName" : "Larry", "UserPost" : [ "Hi", "Hello" ] }
{ "_id" : ObjectId("..."), "UserName" : "Chris", "UserPost" : [ "Hi", "Good Morning" ] }
{ "_id" : ObjectId("..."), "UserName" : "Robert", "UserPost" : [ "Awesome" ] }
3. สร้างดัชนีบนฟิลด์อาร์เรย์ (Optional)
> db.distinctAggregation.ensureIndex({"UserPost":1});
4. ดึงค่าที่ไม่ซ้ำจากฟิลด์ UserPost
> db.distinctAggregation.distinct("UserPost");
[ "Awesome", "Good Morning", "Hello", "Hi" ]
จุดสำคัญ
distinct()จะดูค่าทุกค่าในอาร์เรย์ของทุกเอกสาร แล้วคืนค่าที่ไม่ซ้ำกัน- ผลลัพธ์เป็นอาร์เรย์ของค่าที่ unique
- สามารถสร้างดัชนีบนฟิลด์อาร์เรย์เพื่อเพิ่มประสิทธิภาพได้
- ใช้ได้กับฟิลด์ทั่วไป ไม่ใช่แค่อาร์เรย์
สรุป
db.collection.distinct("fieldName") เป็นวิธีที่ง่ายและรวดเร็วที่สุดในการดึงค่า distinct จากฟิลด์อาร์เรย์หรือฟิลด์ทั่วไปใน MongoDB