Để tìm kiếm văn bản, bạn cần sử dụng $ text cùng với $ search. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo156.createIndex({"StudentName":"text"});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo156.insertOne({"StudentName":"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3547e8fdf09dd6d08539e6")
}
> db.demo156.insertOne({"StudentName":"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3547f2fdf09dd6d08539e7")
}
> db.demo156.insertOne({"StudentName":"John Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3547f7fdf09dd6d08539e8")
} 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.demo156.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e3547e8fdf09dd6d08539e6"), "StudentName" : "Chris Brown" }
{ "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" } Sau đây là truy vấn để triển khai tìm kiếm văn bản trong MongoDB -
> db.demo156.find({ $text: { $search: "John" } } ) Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }