Để tạo index cho nhiều trường cùng lúc (compound index) trong MongoDB, bạn sử dụng phương thức createIndex() (hoặc ensureIndex() ở các phiên bản cũ) với một object chỉ định các trường và thứ tự (1: tăng dần, -1: giảm dần). Index kết hợp giúp tối ưu hóa truy vấn lọc, sắp xếp trên nhiều trường đồng thời.
1. Tạo index kết hợp
> db.demo53.createIndex({ "StudentFirstName": 1, "StudentAge": 1 });
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
> db.demo53.createIndex({ "StudentFirstName": 1, "StudentCountryName": 1 });
{ "createdCollectionAutomatically": false, "numIndexesBefore": 2, "numIndexesAfter": 3, "ok": 1 }
Lưu ý: ensureIndex() đã deprecated từ MongoDB 3.0, nên dùng createIndex().
2. Chèn dữ liệu mẫu
> db.demo53.insertOne({ "StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US" });
> db.demo53.insertOne({ "StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK" });
> db.demo53.insertOne({ "StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS" });
3. Xem dữ liệu
> db.demo53.find();
Kết quả:
{ "_id": ObjectId("..."), "StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US" }
{ "_id": ObjectId("..."), "StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK" }
{ "_id": ObjectId("..."), "StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS" }
Quan trọng: Thứ tự trường trong index kết hợp rất quan trọng. Index {a:1, b:1} hỗ trợ truy vấn trên a đơn lẻ hoặc a,b cùng lúc, nhưng KHÔNG hỗ trợ truy vấn chỉ trên b đơn lẻ.