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

Index trường lồng nhau trong MongoDB (dot notation)

Tạo index cho trường bên trong object lồng nhau

MongoDB hỗ trợ index trên trường nested document bằng dot notation trong định nghĩa index.

Tạo dữ liệu và index

> db.demo323.insertOne({"details": {"Name": "Chris", "Age": 34}});
> db.demo323.insertOne({"details": {"Name": "David", "Age": 31}});
> db.demo323.insertOne({"details": {"Name": "Bob", "Age": 28}});
> db.demo323.createIndex({ "details.Name": 1 });

Truy vấn sử dụng index

> db.demo323.find({ "details.Name": "Bob" });

Kết quả

{ "_id": ObjectId("..."), "details": { "Name": "Bob", "Age": 28 } }

Lợi ích: Index trên details.Name cho phép truy vấn nhanh mà không cần quét toàn bộ collection. Index này cũng hỗ trợ sort trên trường lồng nhau.

Lưu ý: Dùng createIndex() thay vì ensureIndex() (deprecated).