正则表达式匹配mongodb中的整个单词

编程入门 行业动态 更新时间:2024-10-12 01:29:18
本文介绍了正则表达式匹配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"}}]}

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

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

更多推荐

正则表达式匹配mongodb中的整个单词

本文发布于:2023-11-02 12:07:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   正则表达式   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!