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

Tìm kiếm toàn văn bản (Text Search) trong MongoDB với $text và $search

MongoDB hỗ trợ tìm kiếm văn bản (full-text search) qua Text Index và toán tử $text/$search. Phù hợp cho tìm kiếm mô tả, bài viết, tên sản phẩm...

Tạo Text Index và dữ 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") }

Xem dữ liệu

> db.demo156.find();
{ "_id" : ObjectId("5e3547e8fdf09dd6d08539e6"), "StudentName" : "Chris Brown" }
{ "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" }

Tìm kiếm từ khóa "John"

> db.demo156.find({ $text: { $search: "John" } } )

Kết quả

{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }

Tính năng nâng cao:

  • $search: "\"John Doe\"" – tìm cụm từ chính xác (phrase).
  • $search: "John -Doe" – tìm John nhưng loại trừ Doe.
  • Sắp xếp theo độ liên quan: { score: { $meta: "textScore" } } trong sort/project.
  • Chỉ tạo được một text index trên một collection (có thể compound nhiều trường).
  • Hỗ trợ nhiều ngôn ngữ, stop words, stemming.