MongoDB:使用变量进行文本搜索(完全匹配) [英] MongoDB: Text search (exact match) using variable
问题描述
MongoDB 3.4
我有一个变量值. val1 =小堡"
我需要在集合存储中搜索(名称字段上带有文本索引),其文档为
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}})
它返回_id:4文档,因为它包含Fort.
it returns the _id : 4 document, since it contains Fort.
我需要做一个精确匹配,但要使用变量.
I need to do an exact match but using the variable.
仅当val1 ="Fort Coffee"时,才返回上述搜索结果
The above search should return only when val1 = "Fort Coffee"
推荐答案
进行文本搜索时,它具有许多内部步骤,例如标记您的工作,分析单词的最低词干(例如,将烹饪和烹饪都匹配)源自基础工作烹饪").如果您期望完全匹配,则实际上不是在寻找文字搜索,而是在寻找普通查询.
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.
因此
如果您这样做:
db.City.find({$text:{$search: "Fort Minor"}})
它将尝试查找其中包含要塞,未成年人,少数民族,福特等的所有文档.
It will try to find all documents which have fort, minor, minority, forting etc in it.
如果您执行以下操作:
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"})
它不会满足您的期望.
要解决此问题,请使用正则表达式:
To resolve this, go for regular expression :
db.user.find( { name: /^Fort Minor$/i } );
这篇关于MongoDB:使用变量进行文本搜索(完全匹配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!