Search code examples
gomgo

Case insensitive MongoDB query from Go


I have this json file:

[{
    "name": "chetan",
    "age": 23,
    "hobby": ["cricket", "football"]
}, {
    "name": "raj",
    "age": 24,
    "hobby": ["cricket", "golf"]
}]

I use this Go code to search the data:

id := "ket" 
regex := bson.M{"$regex": bson.RegEx{Pattern: id}} 
err = c.Find(bson.M{"hobby": regex}).All(&result)

It finds if searched by the same string like "cricket" but if I search string like this "Cricket", it does not find it.


Solution

  • Add Options: "i" to your RegEx.

    bson.M{"$regex": bson.RegEx{Pattern: id, Options: "i"}}