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

สร้าง Compound Index พร้อมฟิลด์ค่าคงที่ใน MongoDB

ใช้ createIndex() เพื่อสร้าง Compound Index (ดัชนีรวม) ที่มีฟิลด์ค่าคงที่

สร้าง Compound Index บน StudentName และ StudentAge แบบ Unique:

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

เพิ่มเอกสาร (บางรายการมี Age บางรายการไม่มี):

> db.compoundIndexDemo.insertOne({"StudentName":"Chris"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c1d25ddae1f53b62207") } 
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c5625ddae1f53b62209") } 
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":22}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c5b25ddae1f53b6220a") } 
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23}); 
2019-12-29T12:19:02.225+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : \"Chris\", : 23.0 }", "op" : { "_id" : ObjectId("5e084c5e25ddae1f53b6220b"), "StudentName" : "Chris", "StudentAge" : 23 } })

แสดงเอกสารทั้งหมด (เอกสาร Chris Age 23 ที่ 2 ไม่ได้เพิ่ม):

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

ผลลัพธ์ - มี 3 เอกสาร: Chris (ไม่มี Age), Chris Age 23, Chris Age 22: