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

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

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


当前回答

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

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

参考:$where

其他回答

如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

结果与:

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

您有两个选择:

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)

下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。

您可以使用包含单词的正则表达式,例如like。也可以使用$options=>i进行不区分大小写的搜索。

包含字符串

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

不包含字符串,仅包含正则表达式

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

完全不区分大小写的字符串

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

以字符串开头

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

以字符串结尾

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。

在Go和mgo驱动程序中:

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

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