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

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

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


当前回答

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

其他回答

正则表达式的处理成本很高。

另一种方法是创建文本索引,然后使用$search进行搜索。

创建要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})

查找结果的一种方法相当于类似查询:

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

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

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

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

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

使用如下匹配的正则表达式。“i”显示不区分大小写。

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);

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

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

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

有多种方法可以实现这一点。

最简单的一个:

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

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

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

更多详细信息可以在$regex中找到。