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

Index, sắp xếp và phân trang với trường tùy chỉnh trong MongoDB

Kết hợp tạo index phức hợp (compound index), sắp xếp và phân trang (limit/skip) để truy vấn hiệu quả.

Tạo index và collection:

> db.demo373.createIndex({"Name":1,"CountryName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo373.insertOne({"Name":"Chris","Age":22,"CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e59ffde2ae06a1609a00aff") }
> db.demo373.insertOne({"Name":"David","Age":21,"CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e59ffe82ae06a1609a00b00") }
> db.demo373.insertOne({"Name":"Bob","Age":23,"CountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e59fff42ae06a1609a00b01") }
> db.demo373.insertOne({"Name":"John","Age":21,"CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e59ffff2ae06a1609a00b02") }
> db.demo373.insertOne({"Name":"Carol","Age":23,"CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5a00082ae06a1609a00b03") }

Xem dữ liệu:

> db.demo373.find();
{ "_id" : ObjectId("5e59ffde2ae06a1609a00aff"), "Name" : "Chris", "Age" : 22, "CountryName" : "US" }
{ "_id" : ObjectId("5e59ffe82ae06a1609a00b00"), "Name" : "David", "Age" : 21, "CountryName" : "AUS" }
{ "_id" : ObjectId("5e59fff42ae06a1609a00b01"), "Name" : "Bob", "Age" : 23, "CountryName" : "UK" }
{ "_id" : ObjectId("5e59ffff2ae06a1609a00b02"), "Name" : "John", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e5a00082ae06a1609a00b03"), "Name" : "Carol", "Age" : 23, "CountryName" : "AUS" }

Truy vấn: sắp xếp Name tăng, Age tăng, bỏ 2 bản ghi đầu, lấy 3 bản ghi (trang 2, size=3):

> db.demo373.find().sort({"Name":1, "Age":1}).limit(4).skip(2);

Kết quả:

Tối ưu hóa:

  • Index {Name:1, CountryName:1} hỗ trợ sắp xếp {Name:1, Age:1} **không hoàn toàn** (thiếu Age). Nên tạo index {Name:1, Age:1} để tránh in-memory sort.
  • skip() chậm trên offset lớn. Thay bằng range query trên _id hoặc trường sort (keyset pagination).
  • Luôn dùng explain() kiểm tra execution plan.