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

วิธีดึงค่าที่ไม่ซ้ำกัน (Distinct) จากอาร์เรย์ของออบเจ็กต์ใน MongoDB


ใช้ distinct() กับ Dot Notation

เมธอด distinct() รองรับ dot notation เข้าถึงฟิลด์ภายในอาร์เรย์ของออบเจ็กต์ได้โดยตรง

ตัวอย่างข้อมูล

> db.demo442.insertOne({
  "Information": [
    { "FirstName": "John", "Age": 21 },
    { "FirstName": "Sam", "Age": 23 },
    { "FirstName": "John", "Age": 24 },
    { "FirstName": "Carol", "Age": 20 },
    { "FirstName": "Sam", "Age": 22 }
  ]
});

แสดงข้อมูล

> db.demo442.find();

Query ดึง FirstName ที่ไม่ซ้ำกัน

> db.demo442.distinct("Information.FirstName");

ผลลัพธ์

[ "Carol", "John", "Sam" ]

คำอธิบาย

  • Information.FirstName - dot notation เข้าถึง FirstName ในทุกอิลิเมนต์ของอาร์เรย์ Information
  • MongoDB จะดึงค่าจากทุกอิลิเมนต์ แล้วคืนค่าเฉพาะค่าที่ไม่ซ้ำกัน (unique)
  • ผลลัพธ์เป็นอาร์เรย์เรียงตามลำดับ Unicode

ตัวอย่างเพิ่มเติม

// ดึงอายุที่ไม่ซ้ำกัน
db.demo442.distinct("Information.Age");
// ผลลัพธ์: [20, 21, 22, 23, 24]

// ดึงค่า distinct พร้อม filter
db.demo442.distinct("Information.FirstName", { "Information.Age": { $gte: 22 } });
// ผลลัพธ์: ["Sam", "John"] (เฉพาะอายุ 22 ขึ้นไป)

ข้อจำกัด

distinct() ไม่รองรับ aggregation pipeline เต็มรูปแบบ หากต้องการคำนวณซับซ้อน ให้ใช้ $group ใน aggregate() แทน