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

MongoDB Query ดึงค่า FirstName ที่ไม่ซ้ำกันด้วย distinct()

Method distinct() ใน MongoDB ใช้สำหรับดึงค่า Unique (Distinct Values) ของฟิลด์ที่ระบุ เนื้อหานี้สาธิตการหาค่า FirstName ที่ไม่ซ้ำกันจาก Collection ที่มีข้อมูลซ้ำ

ตัวอย่างข้อมูลทดสอบ

> db.demo303.insertOne({FirstName:"Chris",LastName:"Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea0f6f8647eb59e56202f") }

> db.demo303.insertOne({FirstName:"John",LastName:"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea104f8647eb59e562030") }

> db.demo303.insertOne({FirstName:"Chris",LastName:"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea10df8647eb59e562031") }

> db.demo303.insertOne({FirstName:"John",LastName:"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea121f8647eb59e562032") }

> db.demo303.insertOne({FirstName:"David",LastName:"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4ea136f8647eb59e562033") }

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

> db.demo303.find().pretty();
{
    "_id" : ObjectId("5e4ea0f6f8647eb59e56202f"),
    "FirstName" : "Chris",
    "LastName" : "Brown"
}
{
    "_id" : ObjectId("5e4ea104f8647eb59e562030"),
    "FirstName" : "John",
    "LastName" : "Doe"
}
{
    "_id" : ObjectId("5e4ea10df8647eb59e562031"),
    "FirstName" : "Chris",
    "LastName" : "Smith"
}
{
    "_id" : ObjectId("5e4ea121f8647eb59e562032"),
    "FirstName" : "John",
    "LastName" : "Smith"
}
{
    "_id" : ObjectId("5e4ea136f8647eb59e562033"),
    "FirstName" : "David",
    "LastName" : "Miller"
}

Query distinct FirstName

> db.demo303.distinct("FirstName");

ผลลัพธ์

[ "Chris", "John", "David" ]

ข้อมูลเพิ่มเติม

  • distinct("field") คืนค่า Array ของ Unique Values
  • สามารถเพิ่ม Query Filter ได้: db.collection.distinct("field", { query })
  • ตัวอย่าง: db.demo303.distinct("FirstName", { LastName: "Smith" }) → ["Chris", "John"]
  • มีข้อจำกัด: ผลลัพธ์ต้องไม่เกิน 16MB (BSON Document Size Limit)
  • ใช้ Index ได้หากมี Index บน Field ที่ Distinct