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

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

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


当前回答

这必须是:

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

或类似:

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

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

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

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

其他回答

您可以使用where语句构建任何JavaScript脚本:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

参考:$where

在SQL中,“like”查询如下所示:

select * from users where name like '%m%'

在MongoDB控制台中,如下所示:

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

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

此外,pretty()方法将在所有地方生成一个格式化的JSON结构,这样可读性更强。

您已经得到了答案,但要匹配不区分大小写的正则表达式,可以使用以下查询:

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

/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。

有多种方法可以实现这一点。

最简单的一个:

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

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

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

更多详细信息可以在$regex中找到。

您可以使用MongoDB 2.6的新功能:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});