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

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

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


当前回答

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

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

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

其他回答

对于Node.js中的Mongoose:

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

似乎有理由同时使用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.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

其中i用于不区分大小写的提取数据。

我们还可以通过另一种方式获得结果:

db.collection.find({"name":/aus/})

上面将提供名称中包含aus的结果。

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

例如

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

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);