Search code examples
regexmongodbgomongo-go

Partial matches using mongo's primitive package


I am using Mongo's Primitive package to get a bson value based on what was submitted. This is what I am currently doing

school = "Havard"
value = primitive.Regex{Pattern: school, Options: ""} 

This will only match bson values that are Havard, how do I make this regex case insensitive and make it match for example, hava

In all, if I use hava for a search, I should also get Havard


Solution

  • The expression primitive.Regex{Pattern: school} matches substrings too, but it's not case insensitive. Use the "i" option to make it case insensitive:

    value = primitive.Regex{Pattern: school, Options: "i"}
    

    Also note that if the value of school contains special regexp characters, that might give you unexpected results or errors. So best is to quote it with e.g. using regexp.QuoteMeta():

    value = primitive.Regex{Pattern: regexp.QuoteMeta(school), Options: "i"}