我正在寻找一个操作符,它允许我检查字段的值是否包含某个字符串。

喜欢的东西:

db.users.findOne({$contains:{"username":"son"}})

这可能吗?


当前回答

这样就可以了

db.users.find({ username: { $in: [ /son/i ] } });

i只是为了防止限制匹配单个字母的大小写。

您可以在MongoDB文档中查看$regex文档。 这里有一个链接:https://docs.mongodb.com/manual/reference/operator/query/regex/

其他回答

如果正则表达式包含一个变量,请确保转义它。

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

可以这样使用

new RegExp(escapeRegExp(searchString), 'i')

或者在mongoDb查询中

{ '$regex': escapeRegExp(searchString) }

在这里发表同样的评论

对于聚合框架


领域搜索

('$options': 'i'用于不区分大小写搜索)

db.users.aggregate([
    {
        $match: {
            'email': { '$regex': '@gmail.com', '$options': 'i' }
        }
    }
]);

全文检索

(仅适用于文本索引的字段

db.articles.aggregate([
    {
        $match: { $text: { $search: 'brave new world' } }
    }
])

您可以使用以下代码来实现。

db.users.findOne({"username" : {$regex : "son"}});

如何在RegExp匹配中忽略HTML标签:

var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';

var rx = '';
searchString.split(' ').forEach(e => {
  rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});

rx = new RegExp(rx, 'igm');

console.log(text.match(rx));

这可能很容易变成一个MongoDB聚合过滤器。

如果需要搜索多个属性,可以使用$or。例如

Symbol.find(
  {
    $or: [
      { 'symbol': { '$regex': input, '$options': 'i' } },
      { 'name': { '$regex': input, '$options': 'i' } }
    ]
  }
).then((data) => {
  console.log(data)
}).catch((err) => {
  console.log(err)
})

在这里,您将根据输入是否包含在符号属性或名称属性中进行搜索。