检查字段是否包含字符串

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

喜欢的东西:

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

这可能吗?

717407 次浏览

由于Mongo shell支持正则表达式,这是完全可能的。

db.users.findOne({"username" : /.*son.*/});

如果我们想让查询不区分大小写,我们可以使用"i"选项,如下所示:

db.users.findOne({"username" : /.*son.*/i});

看到:# EYZ0

https://docs.mongodb.com/manual/reference/sql-comparison/

http://php.net/manual/en/mongo.sqltomongo.php

MySQL

SELECT * FROM users WHERE username LIKE "%Son%"

MongoDB

db.users.find({username:/Son/})

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

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

下面是通过Python连接MongoDB时必须做的事情

db.users.find({"username": {'$regex' : '.*' + 'Son' + '.*'}})

你也可以使用一个变量名来代替'Son',因此字符串连接。

从2.4版开始,您可以在字段上创建文本索引来进行搜索,并使用美元的文本操作符进行查询。

首先,创建索引:

# EYZ0

然后,搜索:

# EYZ0

基准测试(~150K文档):

  • Regex(其他答案)=> 5.6-6.9秒
  • 文本搜索=> .164-。201秒

注:

  • 一个集合只能有一个文本索引。如果想搜索任何字符串字段,可以使用通配符文本索引,如下所示:db.collection.createIndex( { "$**": "text" } )
  • 文本索引可以很大。它为插入的每个文档的每个索引字段中的每个唯一后词干词包含一个索引条目。
  • 文本索引的构建时间要比普通索引长。
  • 文本索引不存储短语或关于文档中单词接近度的信息。因此,当整个集合适合RAM时,短语查询将更有效地运行。

由于这是在搜索引擎的第一个点击之一,上面没有一个似乎适用于MongoDB 3。X,这里有一个正则表达式搜索是有效的:

db.users.find( { 'name' : { '$regex' : yourvalue, '$options' : 'i' } } )

不需要创建额外的索引或类似的。

这是完成这项任务最简单的方法

如果您希望查询为区分大小写的

db.getCollection("users").find({'username':/Son/})

如果您希望查询为不区分大小写

db.getCollection("users").find({'username':/Son/i})

如何在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聚合过滤器。

理想答案它的使用指数 i选项不区分大小写

db.users.findOne({"username" : new RegExp(search_value, 'i') });

这样就可以了

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' } }
}
])

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

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

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

如果正则表达式在聚合解决方案中不起作用,并且您有嵌套对象。试试这个聚合管道:(如果你的对象结构很简单,那么就从下面的查询中删除其他条件):

db.user.aggregate({$match:
{$and:[
{"UserObject.Personal.Status":"ACTV"},
{"UserObject.Personal.Address.Home.Type":"HME"},
{"UserObject.Personal.Address.Home.Value": /.*son.*/ }
]}}
)

另一种方法是像这样直接查询:

db.user.findOne({"UserObject.Personal.Address.Home.Value": /.*son.*/ });

我使用这个代码,它的工作搜索子字符串

db.users.find({key: { $regex: new RegExp(value, 'i')}})