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

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

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


当前回答

将模板文字与变量一起使用也有效:

{“firstname”:{$regex:`^${req.body.firstname}.*`,$options:'si'}}

其他回答

In

使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go

您可以执行以下操作:

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" }

为了以防万一,有人正在寻找一种SQL LIKE类型的查询,以查找包含字符串数组而不是字符串的键,这里是:

db.users.find({"name": {$in: [/.*m.*/]}})

您有两个选择:

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

or

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

对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。

关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。

对于Go驱动程序:

filter := bson.M{
    "field_name": primitive.Regex{
        Pattern: keyword,
        Options: "",
    },
}
cursor, err := GetCollection().Find(ctx, filter)

在$in查询中使用正则表达式(MongoDB文档:$in):

filter := bson.M{
    "field_name": bson.M{
        "$in": []primitive.Regex{
            {
                Pattern: keyword,
                Options: "",
            },
        }
    }
}
cursor, err := GetCollection().Find(ctx, filter)