Để tạo compound multikey index (chỉ mục kết hợp trên trường mảng), dùng ensureIndex() (alias của createIndex()). Tạo collection:
> db.demo678.ensureIndex({id:1,"details.userId":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo678.insertOne({
id: 101,
"details": [
{ "userId": "1001", "userName": "Chris" },
{ "userId": "1002", "userName": "David" }
],
"otherDetails": [
{ CountryName: "US", EmailId: ["Chris@gmail.com","David@gmail.com"] }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea4276904263e90dac943fc") }
Hiển thị dữ liệu:
> db.demo678.find();
Kết quả:
Giải thích index compound multikey:
{id: 1, "details.userId": 1}- index trên id (scalar) + details.userId (array)- MongoDB tự động tạo **multikey index** cho trường mảng
details.userId - Mỗi phần tử trong mảng details tạo một entry index riêng
- Hỗ trợ query:
find({id: 101, "details.userId": "1001"})
Hạn chế: Chỉ được **MỘT** trường multikey trong compound index. Không thể tạo index trên cả details.userId và otherDetails.EmailId cùng lúc (cả 2 đều là mảng).
Xem index: db.demo678.getIndexes(). Xóa: db.demo678.dropIndex("id_1_details.userId_1").