Tạo index duy nhất (unique: true) trên trường thường xuyên truy vấn để tăng tốc độ. Tạo collection và index:
> db.demo193.createIndex({ "LastName": 1 }, { unique: true });
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
> db.demo193.insertOne({ "FirstName": "John", "LastName": "Doe" });
{ "acknowledged": true, "insertedId": ObjectId("5e3ade1803d395bdc21346d1") }
> db.demo193.insertOne({ "FirstName": "John", "LastName": "Smith" });
{ "acknowledged": true, "insertedId": ObjectId("5e3ade1f03d395bdc21346d2") }
> db.demo193.insertOne({ "FirstName": "David", "LastName": "Miller" });
{ "acknowledged": true, "insertedId": ObjectId("5e3ade2803d395bdc21346d3") }
Hiển thị document.
Truy vấn tìm LastName="Smith" (sẽ dùng index):
> db.demo193.find({ "LastName": "Smith" });
Kết quả:
{ "_id": ObjectId("5e3ade1f03d395bdc21346d2"), "FirstName": "John", "LastName": "Smith" }