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

Tạo index trong MongoDB

Để tạo index trong MongoDB, dùng phương thức createIndex() (thay thế ensureIndex() đã deprecated).

Ví dụ: Tạo collection và index unique trên trường UserCountryName:

> db.createCollection("creatingUniqueIndexDemo");
{ "ok" : 1 }
> db.creatingUniqueIndexDemo.createIndex({ "UserCountryName": 1 }, { unique: true });
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

Chèn dữ liệu kiểm tra unique constraint:

> db.creatingUniqueIndexDemo.insertOne({"UserName":"John","UserAge":21,"UserCountryName":"US"});
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Mike","UserAge":23,"UserCountryName":"UK"});
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"US"});
// Lỗi: E11000 duplicate key error collection: ... UserCountryName_1 dup key: { : "US" }
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"AUS"});

Xem dữ liệu:

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

Kết quả (chỉ 3 tài liệu, bản US thứ 2 bị từ chối):

{ "_id" : ObjectId(...), "UserName" : "John", "UserAge" : 21, "UserCountryName" : "US" }
{ "_id" : ObjectId(...), "UserName" : "Mike", "UserAge" : 23, "UserCountryName" : "UK" }
{ "_id" : ObjectId(...), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "AUS" }

Các loại index phổ biến:

  • Single field: { field: 1 } (tăng) hoặc -1 (giảm)
  • Compound: { field1: 1, field2: -1 }
  • Unique: { unique: true }
  • Text: { field: "text" }
  • TTL: { expireAfterSeconds: 3600 }