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

วิธีดึงค่า Distinct พร้อมเรียงลำดับ (Sorted) ใน MongoDB

ใช้เมธอด distinct() ตามด้วย .sort() เพื่อดึงค่าที่ไม่ซ้ำและเรียงลำดับอัตโนมัติ

รูปแบบคำสั่ง

db.collection.distinct("fieldName").sort();

ตัวอย่างเต็มรูปแบบ

1. สร้างข้อมูลตัวอย่าง (มีค่าซ้ำ)

> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":30,"StudentName":"Chris","StudentAge":22});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});

2. แสดงข้อมูลทั้งหมด

> db.getDistinctWithSortedDataDemo.find().pretty();

3. Distinct + Sort: StudentName

> db.getDistinctWithSortedDataDemo.distinct("StudentName").sort();
[ "Bob", "Carol", "Chris", "John" ]

4. Distinct + Sort: StudentAge

> db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort();
[ 20, 21, 22, 23 ]

รายละเอียดการทำงาน

  • distinct("field") คืน Array ของค่า Unique
  • .sort() เรียง Array ตามค่าเริ่มต้น (String: A-Z, Number: น้อย-มาก)
  • ทำงานบน MongoDB Shell (JavaScript Array.sort())

วิธีทางเลือก: Aggregation (สำหรับข้อมูลเยอะ/Complex Sort)

db.collection.aggregate([
    { $group: { _id: "$fieldName" } },
    { $sort: { _id: 1 } },
    { $project: { _id: 0, value: "$_id" } }
]);

วิธีนี้ทำงานฝั่ง Server เหมาะกับข้อมูล Volume ใหญ่

สรุป

  • db.collection.distinct("field").sort() - ใช้ง่าย สำหรับข้อมูลปานกลาง
  • String เรียง A-Z, Number เรียง น้อย-มาก
  • ข้อมูลเยอะหรือต้องการ Sort แบบ Custom ใช้ Aggregation
  • Distinct ใช้ Index ได้ (ถ้ามี Index บนฟิลด์นั้น)