Để lập chỉ mục trường văn bản lớn, hãy sử dụng ensureIndex () cùng với $ regex để tìm kiếm văn bản. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo46.ensureIndex({"Name":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo46.insertOne({"Name":"John Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267004cfb11e5c34d898ed")
}
> db.demo46.insertOne({"Name":"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267009cfb11e5c34d898ee")
}
> db.demo46.insertOne({"Name":"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267011cfb11e5c34d898ef")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo46.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" }
{ "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e267011cfb11e5c34d898ef"), "Name" : "Chris Brown" } Sau đây là truy vấn để lập chỉ mục trường văn bản lớn để làm cho truy vấn nhanh hơn -
> db.demo46.find({ Name: { $regex:/^John/}}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" }