正则表达式匹配mongodb中的整个单词 [英] regular expression to match whole word in mongodb

查看:82
本文介绍了正则表达式匹配mongodb中的整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像下面的情况一样在MongoDB中搜索结果.

I want to search the result in MongoDB like in the following scenario.

我有类似Hello World, I am here.

我的查询是:

{"$or": [{"data.title": {"$regex":  search}}]}; //search = Hello

所以我正在使用$ regex搜索它.但是问题是,如果我键入search = H,那么它再次返回数据

So i am searching it using $regex. but the problem is that if i type search = H, then again its returning the data

我只想搜索完整的单词. (例如:Hello或World)(不是基于字符)(例如:H或e)

I want to search on the basis complete word only. (example: Hello or World) not on the basis of Characters (example: H or e)

推荐答案

您可以使用\ b(单词边界)运算符,例如:

You can use the \b (word boundary) operator, eg:

{"$or": [{"data.title": {"$regex": /\bHello\b/i}}]}

通过这种方式,搜索"/\ bH \ b/"将与"Hello"不匹配.

In this way, searching for "/\bH\b/" won't match "Hello".

否则,请在标题字段上使用$ text索引,然后进行$ text搜索:

Otherwise, use a $text index on your title field, then do a $text search:

{"$or": [{$text:{$search:"Hello"}}]}

有关文本搜索的更多信息,请参阅以下文档: http://docs .mongodb.org/manual/administration/indexes-text/

For more information about text search, look at the documentation: http://docs.mongodb.org/manual/administration/indexes-text/

这篇关于正则表达式匹配mongodb中的整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆