MongoDB: Text search (exact match) using variable

▼魔方 西西 提交于 2019-12-08 03:56:55

问题


MongoDB 3.4

I have a value in a variable. val1 = "Fort Minor"

I need to search in a collection stores (with text index on name field) with documents as

db.stores.insert([
     { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
     { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
     { _id: 3, name: "Coffee Shop", description: "Just coffee" },
     { _id: 4, name: "Fort Coffee", description: "Discount clothing" },
     { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
])


when I text search the collection using the variable

db.City.find({$text:{$search: val1}})

it returns the _id : 4 document, since it contains Fort.

I need to do an exact match but using the variable.

The above search should return only when val1 = "Fort Coffee"


回答1:


When you do text search, it has many internal steps like tokenizing your work, analyzing the lowest stem of the word(e.g. to match cooking & coocked as both are derived from basic work "cook"). If you are expecting an exact match, you are not actually looking for a texual search but you are looking for a normal query.

Hence,

If you do this :

db.City.find({$text:{$search: "Fort Minor"}})

It will try to find all documents which have fort, minor, minority, forting etc in it.

If you do below :

db.City.find({ name : "Fort Minor"})

If will give you the document with exact match.

However, here is the catch :

IF you search all lowercase like :

db.City.find({ name : "fort minor"})

It will not give you what you are expecting.

To resolve this, go for regular expression :

db.user.find( { name: /^Fort Minor$/i } );


来源:https://stackoverflow.com/questions/43779319/mongodb-text-search-exact-match-using-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!