MongoDB如何使用正则表达式进行搜索,但避免区分大小写?

huangapple go评论92阅读模式
英文:

MongoDB how to search by using regex but avoiding case sensitive?

问题

这是我目前完成的部分:

filter := bson.M{
    "$or": bson.A{
        bson.M{"title": bson.M{"$regex": "input"}},
        bson.M{"author": bson.M{"$regex": "input"}},
        bson.M{"content": bson.M{"$regex": "input"}},
    },
}

p.postProposalCollection.Find(ctx, filter)

但它是区分大小写的,有没有办法将列 titleauthorcontent 转换为小写,然后尝试使用正则表达式进行搜索。

英文:

Here is what I have done so far

filter := bson.M{
    "$or": bson.A{
        bson.M{"title": bson.M{"$regex": "input"}},
        bson.M{"author": bson.M{"$regex": "input"}},
        bson.M{"content": bson.M{"$regex": "input"}},
    },
}

p.postProposalCollection.Find(ctx, filter)

but it is case sensitive, is there anyway to lowercase the column title, author, content then try to search with regex.

答案1

得分: 1

要进行不区分大小写的正则表达式搜索,您可以使用带有"i"标志的Regex原语:

bson.M{"title": bson.M{"$regex": primitive.Regex{Pattern: "input", Options: "i"}}},

有关详细信息,请参阅这里这里

英文:

To do the case-insensitive regex search, you can use the Regex primitive with "i" flag:

bson.M{"title": bson.M{"$regex": primitive.Regex{Pattern: "input", Options: "i"}}},

See here and here for details.

huangapple
  • 本文由 发表于 2022年6月29日 09:14:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/72794725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定