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

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

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


当前回答

您可以使用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"
    }
});

其他回答

可以使用正则表达式进行查询:

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

如果字符串来自用户,则可能需要在使用该字符串之前对其进行转义。这将防止来自用户的文字字符被解释为正则表达式标记。

例如,如果不转义,搜索字符串“A”也将匹配“AB”。在使用字符串之前,可以使用一个简单的替换来转义字符串

function textLike(str) {
  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  return new RegExp(escaped, 'i');
}

所以现在,字符串变成了一个不区分大小写的模式,同时匹配文字点。例子:

>  textLike('A.');
<  /A\./i

现在,我们可以随时生成正则表达式了:

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

Use:

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。

我找到了一个免费的工具来将MySQL查询转换为MongoDB:http://www.querymongo.com/

我检查了几个问题。在我看来,几乎所有这些都是正确的。据此,答案是

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

还可以按如下方式使用通配符过滤器:

{"query": { "wildcard": {"lookup_field":"search_string*"}}}

请务必使用*。

对于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)