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

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

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


当前回答

在MongoDb中,可以使用likeusingMongoDB引用运算符正则表达式(regex)。

对于相同的Ex。

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

MongoDb

    1) db.users.find({ "name": { "$regex": "m", "$options": "i" } })

    2) db.users.find({ "name": { $regex: new RegExp("m", 'i') } })

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

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

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

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

MongoDb Any of Above with /^String/

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

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

MongoDb Any of Above with /String$/

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

其他回答

在Go和mgo驱动程序中:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

其中结果是所查找类型的结构实例。

对于Node.js中的Mongoose:

db.users.find({'name': {'$regex': '.*sometext.*'}})

在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结构,这样可读性更强。

似乎有理由同时使用JavaScript/regex_pattern/模式和MongoDB{“$regex”:“regex_pattern”}模式。请参阅:MongoDB RegEx语法限制

这不是一个完整的正则表达式教程,但在看到上面一篇投票率很高的模棱两可的帖子后,我受启发运行这些测试。

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }

这必须是:

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

或类似:

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

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

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

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