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

MongoDB สามารถ Index ค่า Null ได้หรือไม่?

MongoDB สามารถ Index ค่า Null ได้** โดย Default Unique Index จะอนุญาตให้มี Null เพียง 1 Document (Null ถือว่าเป็น Unique Value) เนื้อหานี้สาธิตการสร้าง Unique Index บน Field Value และ Insert Null

สร้าง Unique Index และข้อมูลทดสอบ

> db.demo170.createIndex({"Value": 1}, {unique: true});
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }

> db.demo170.insert({"Value": 100});
WriteResult({ "nInserted": 1 })

> db.demo170.insert({"Value": null});
WriteResult({ "nInserted": 1 })

> db.demo170.insert({"Value": 90});
WriteResult({ "nInserted": 1 })

> db.demo170.insert({"Value": 78});
WriteResult({ "nInserted": 1 })

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

> db.demo170.find();
{
  "_id": ObjectId("5e369b789e4f06af551997da"),
  "Value": 100
}
{
  "_id": ObjectId("5e369b7c9e4f06af551997db"),
  "Value": null
}
{
  "_id": ObjectId("5e369b809e4f06af551997dc"),
  "Value": 90
}
{
  "_id": ObjectId("5e369b969e4f06af551997dd"),
  "Value": 78
}

Query เรียงตาม Value (Index Scan)

> db.demo170.find().sort({Value: 1});

ผลลัพธ์ (Null อยู่หน้าสุด - ค่าน้อยที่สุด)

{
  "_id": ObjectId("5e369b7c9e4f06af551997db"),
  "Value": null
}
{
  "_id": ObjectId("5e369b969e4f06af551997dd"),
  "Value": 78
}
{
  "_id": ObjectId("5e369b809e4f06af551997dc"),
  "Value": 90
}
{
  "_id": ObjectId("5e369b789e4f06af551997da"),
  "Value": 100
}

คำอธิบายและรายละเอียด

  • Null ใน Index: MongoDB Index Null Values โดย Default (ไม่ต้อง Config เพิ่ม)
  • Unique Index + Null: อนุญาต 1 Document เท่านั้น ที่มี Null (เพราะ Null = Null → Duplicate)
  • ลอง Insert Null อีกครั้ง:
    > db.demo170.insert({"Value": null});
        WriteResult({
          "nInserted": 0,
          "writeError": { "code": 11000, "errmsg": "E11000 duplicate key error ... dup key: { : null }" }
        })
  • Sort Order: Null < Numbers < Strings < Objects < Arrays < Binary < ObjectId < Boolean < Date < Timestamp < Regex < MaxKey
  • Sparse Index: หากต้องการ Index เฉพาะ Doc ที่มี Field นั้น (Skip Null/Missing) ใช้ {sparse: true}:
    db.demo170.createIndex({Value: 1}, {unique: true, sparse: true})
    แล้วจะ Insert Null ได้หลาย Document (เพราะ Sparse ไม่ Index Null/Missing)
  • Partial Filter Expression (MongoDB 3.2+): ควบคุม Index ได้ละเอียดกว่า Sparse