Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Thiết lập Compound Index với trường giá trị cố định trong MongoDB

Sử dụng createIndex() để tạo compound index (chỉ mục kết hợp) unique trên nhiều trường.

Tạo compound unique index trên StudentName và StudentAge:

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

Thêm tài liệu: Chris (không có Age), Chris/Age=23, Chris/Age=22 - đều thành công vì cặp (Name, Age) khác nhau:

> 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") }

Thử thêm Chris/Age=23 lần 2 - báo lỗi duplicate key trên compound index:

> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 }

Hiển thị 3 tài liệu được chấp nhận:

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