在 MongoDB 中使用带有文本搜索的正则表达式

Roh*_*nni 5 mongodb node.js

num在集合中的字段上创建了一个文本索引。现在,在传递字符串以从文本索引进行搜索时,我需要使用必须作为字符串传递给$search变量的正则表达式。

我当前的查询工作正常,但是当我向它添加正则表达式时它不起作用。

当前查询:

db.collection.find({$text:{$search:"1234 6789"}},{'id':1})
Run Code Online (Sandbox Code Playgroud)

我需要向 中添加一个正则表达式/类似查询$search以使其类似于

db.collection.find({$text:{$search:"/1234/ /6789/"}},{'id':1})
Run Code Online (Sandbox Code Playgroud)

我从数据库中获取包含“1234”或“6789”等模式的所有值。

我确实尝试过查询,但它给了我一个$search需要一个字符串错误:

db.collection.find({$text:{$search:/1234/}},{'id':1})
Run Code Online (Sandbox Code Playgroud)

Cat*_*ANU 5

为此,您应该使用 $regex MongoDB 运算符:

// Without options
db.collection.find({num: /1234|5678/i});

// Separate options property
db.collection.find({num: {$regex: /1234|5678/, $options: 'i'}});
Run Code Online (Sandbox Code Playgroud)

要在正则表达式中添加多个术语,请使用 | 操作员

$regex 文档和示例

编辑:

要使用值数组查询记录,$in可以使用运算符:

$in 文档和示例