本文介绍了使用mongoose正则表达式与文本在mongo db中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能解释一下两者之间的区别?
Can anyone please explain the difference between:
db.collection.find({ $text: { $search: "dog cat" } })
和
Product.find({ "drug": { "$regex": "cols", "$options": "i" } })
我们什么时候去哪一个?
When should we go for which one ?
推荐答案
用于数据
For data
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" }
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline description" }
要搜索作为单个字符串值的字段sku
,可以使用$regex
To search field sku
which is single string value, could use $regex
db.products.find( { sku: { $regex: /^ABC/i } } )
要搜索作为文本内容值的字段description
,可以使用$text
,当然,我们应该首先在description
上建立文本索引.
Whereas to search field description
which is text content value, could use $text
, of course, we should build text index on description
firstly.
db.products.find( { $text: { $search: "coffee" } } )
为什么不仅正则表达式?
Why not only regex?
-
regular expressions
有其自然的局限性,因为它们缺少任何词干功能,并且无法以简单的方式处理诸如action -superhero
之类的便捷搜索查询. - 它们不能使用传统索引,这会使大型数据集中的查询速度变慢.
regular expressions
have their natural limitations because they lack any stemming functionality and cannot handle convenient search queries such as"action -superhero"
in a trivial way.- they cannot use traditional indexes which makes queries in large datasets really slow.
这里有一个链接他们.
这篇关于使用mongoose正则表达式与文本在mongo db中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!