mongodb regex parameter

mongodb regex parameter

本文关键字:parameter regex mongodb      更新时间:2023-09-26

请参阅以下代码:

{$or: [
        {titleLong: { $regex: regExp } },
        {catalog: { $regex: regExp } },
        {catalogNbr: { $regex: regExp } }
      ]}

我正在尝试查找其字段与某个正则表达式匹配的文档。例如,有一个文档。

{course: {titleLong: "Introduction to analysis of algorithms"},
         {catalog: "cs3333"},
         {catalogNbr: "3333"}}

当用户键入"intro algo"或"3333"或"cs3333"时,应返回文档。我尝试了/(intro|algo)/gi,但它不起作用,因为它返回了所有具有introalgo的文档。此外,g选项似乎不起作用。我还发现了以下正则表达式:

(?=.*'bintro'b)(?=.*'balgo'b).+

但这只会发现单词与intro完全相似的文档,而忽略了introduction

删除先行断言中的单词边界,以便进行部分匹配。

(?=.*intro)(?=.*algo).+

(?=.*intro).*algo.*

别忘了打开不区分大小写的修饰符i

还包括与"3333""cs3333"匹配的图案。

(?=.*intro).*algo.*|^(?:cs)?3333$

定义$regex时可以使用PCRE。您可以返回以特定单词开头的所有条目,并使用(?i)(不区分大小写的搜索)等内联选项。这里有一个例子:

 {titleLong: { { $regex: '(?i).*'bintro.*' } }

或字符串中任何位置包含"intro"的entries:

 {titleLong: { { $regex: '(?i).*intro.*' } }