如何使用bson在GoLang中编写正则表达式的mongodb查询?

I want to do wildcard search in records with firstname in mongodb using go mongodb driver.

I'm using below query to achieve it.

filter := bson.D{{Key: "tenantId", Value: cmd.TenantID}}
if cmd.FirstNameSearch != "" {
    filter = append(filter, bson.E{Key: "firstName",
        Value: bson.M{"$regex": primitive.Regex{Pattern: "^" + cmd.FirstNameSearch + "$", Options: "i"}}})
}

This is not working for me. Could you please correct me if I'm doing anything wrong.

Even in and not in are also not working.

if len(cmd.StatusIn) > 0 {
    filter = append(filter, bson.E{Key: "status", Value: bson.E{Key: "$in", Value: cmd.StatusIn}})
}
if len(cmd.StatusNotIn) > 0 {
    filter = append(filter, bson.E{Key: "status", Value: bson.E{Key: "$nin", Value: cmd.StatusNotIn}})
}

cmd.StatusIn is slice of string ([]string)

Below is an example on how to query with regex with mongo-driver v1.0 :

filter := bson.D{{Key:"foo", Value:99}}
filter = append(filter, bson.E{Key:"bar", Value: bson.D{
        {"$regex", primitive.Regex{Pattern:"^ThisValue.*", Options:"i"}},
    }},
)
cursor, err := collection.Find(context.Background(), filter )

The example above also append a BSON element bson.E for a BSON Document bson.D filter. Similar to your example.

I would suggest to check the struct that you're decoding the result of the query, and/or whether there's a matching document(s) in the collection.