mongodb 检查字段是否包含字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10610131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:39:59  来源:igfitidea点击:

Checking if a field contains a string

mongodb

提问by johnny

I'm looking for an operator, which allows me to check, if the value of a field contains a certain string.

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

Something like:

就像是:

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

Is that possible?

那可能吗?

回答by Parvin Gasimzade

You can do it with the following code.

您可以使用以下代码来完成。

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

回答by James Gan

As Mongo shell support regex, that's completely possible.

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

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

If we want the query to be case-insensitive, we can use "i" option, like shown below:

如果我们希望查询不区分大小写,我们可以使用“i”选项,如下所示:

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

See: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

请参阅:http: //www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

回答by okoboko

As of version 2.4, you can create a text indexon the field(s) to search and use the $textoperator for querying.

从 2.4 版开始,您可以在字段上创建文本索引以进行搜索并使用$text运算符进行查询。

First, create the index:

首先,创建索引:

db.users.createIndex( { "username": "text" } )

db.users.createIndex( { "username": "text" } )

Then, to search:

然后,搜索:

db.users.find( { $text: { $search: "son" } } )

db.users.find( { $text: { $search: "son" } } )

Benchmarks (~150K documents):

基准(~150K 文档):

  • Regex (other answers) => 5.6-6.9 seconds
  • Text Search => .164-.201 seconds
  • 正则表达式(其他答案)=> 5.6-6.9 秒
  • 文本搜索 => .164-.201 秒

Notes:

笔记:

  • A collection can have only one text index. You can use a wildcard text index if you want to search anystring field, like this: db.collection.createIndex( { "$**": "text" } ).
  • A text index can be large. It contains one index entry for each unique post-stemmed word in each indexed field for each document inserted.
  • A text index will take longer to build than a normal index.
  • A text index does not store phrases or information about the proximity of words in the documents. As a result, phrase queries will run much more effectively when the entire collection fits in RAM.
  • 一个集合只能有一个文本索引。如果你想搜索,您可以使用通配符文本索引任何字符串字段中,是这样的:db.collection.createIndex( { "$**": "text" } )
  • 文本索引可能很大。对于插入的每个文档的每个索引字段中的每个唯一后词干词,它包含一个索引条目。
  • 与普通索引相比,文本索引的构建时间更长。
  • 文本索引不存储有关文档中单词邻近度的短语或信息。因此,当整个集合都适合 RAM 时,短语查询将更有效地运行。

回答by Nitai

As this is one of the first hits in the search engines, and none of the above seems to work for MongoDB 3.x, here is one regex search that does work:

由于这是搜索引擎中的第一个热门搜索,并且上述所有内容似乎都不适用于 MongoDB 3.x,因此这是一个有效的正则表达式搜索:

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

No need to create and extra index or alike.

无需创建和额外的索引或类似的。

回答by Anurag Misra

Simplest way to accomplish this task

完成此任务的最简单方法

If you want the query to be case-sensitive

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

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

If you want the query to be case-insensitive

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

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

回答by Patthebug

Here's what you have to do if you are connecting MongoDB through Python

如果您通过 Python 连接 MongoDB,则必须执行以下操作

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

you may also use a variable name instead of 'Son' and therefore the string concatenation.

您也可以使用变量名而不是“Son”,因此使用字符串连接。

回答by Hisham

ideal answer its use index ioption for case-insensitive

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

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

回答by tate

This should do the work

这应该做的工作

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

The iis just there to prevent restrictions of matching single cases of letters.

i是只是为了防止匹配的字母单例的限制。

You can check the $regex documentation on MongoDB documentation. Here's a link: https://docs.mongodb.com/manual/reference/operator/query/regex/

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

回答by Tamás Polgár

How to ignore HTML tags in a RegExp match:

如何在 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));

This is probably very easy to turn into a MongoDB aggregation filter.

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