我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

结果与:

db.users.find({"name": /John/})

其他回答

您可以在MongoDB中使用正则表达式。

例如

db.users.find({"name": /^m/})

如果您使用的是Spring Data MongoDB,可以通过以下方式实现:

String tagName = "m";
Query query = new Query();
query.limit(10);
query.addCriteria(Criteria.where("tagName").regex(tagName));

这必须是:

db.users.find({"name": /.*m.*/})

或类似:

db.users.find({"name": /m/})

您正在查找某个地方包含“m”的内容(SQL的“%”运算符相当于正则表达式“.*”),而不是在字符串开头锚定了“m”。

注意:MongoDB使用的正则表达式比SQL中的“LIKE”更强大。使用正则表达式,您可以创建任何您想象的模式。

有关正则表达式的详细信息,请参阅正则表达式(MDN)。

下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。

您可以使用包含单词的正则表达式,例如like。也可以使用$options=>i进行不区分大小写的搜索。

包含字符串

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

不包含字符串,仅包含正则表达式

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

完全不区分大小写的字符串

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

以字符串开头

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

以字符串结尾

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。

如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您也可以阅读文档-$regex