我想像下面的情况一样在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"}}]}有关文本搜索的更多信息,请参阅以下文档: docs .mongodb/manual/administration/indexes-text/
For more information about text search, look at the documentation: docs.mongodb/manual/administration/indexes-text/
更多推荐
正则表达式匹配mongodb中的整个单词
发布评论