如何用"like"查询MongoDB? [英] How to query MongoDB with "like"?

查看:199
本文介绍了如何用"like"查询MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用SQL的like查询查询某些内容:

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

如何在MongoDB中实现相同目标?我在文档中找不到like的运算符.. >

解决方案

那必须是:

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

或类似的内容:

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

您正在寻找某处包含"m"的东西(SQL的"%"运算符等效于Regexp的".*"),而不是在字符串的开头锚定了"m"的东西. /p>

注意::mongodb使用的正则表达式比sql中的"LIKE"更强大.使用正则表达式,您可以创建您想像的任何模式.

有关正则表达式的更多信息,请参见此链接 https://developer.mozilla.org/zh-CN/docs /Web/JavaScript/Guide/Regular_Expressions

I want to query something with SQL's like query:

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

How to do I achieve the same in MongoDB? I can't find an operator for like in the documentation.

解决方案

That would have to be:

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

or, similar:

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

You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*'), not something that has "m" anchored to the beginning of the string.

note: mongodb uses regular expressions which are more powerful than "LIKE" in sql. With regular expressions you can create any pattern that you imagine.

For more info on regular expressions refer to this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

这篇关于如何用"like"查询MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆