I'm writing a rest api in golang which uses MongoDB. I get some parameters (query, type, tags) from my endpoint url query. Sometimes type and tags are empty (e.g. they are optional). Right now here is my query:
cursor, err := collection.Find(ctx, bson.D{
{"type", eventType},
{"tags", bson.D{{"$in", tags}}},
{"$or",
bson.A{
bson.D{{"title", primitive.Regex{Pattern: ".*" + query + ".*", Options: "i"}}},
bson.D{{"description", primitive.Regex{Pattern: ".*" + query + ".*", Options: "i"}}},
}},
})
I want to have something like if-condition inside of the query or have an $or query operator which checks if a variable is empty. Something like:
cursor, err := collection.Find(ctx, bson.D{
{"$or", bson.D{{"type", eventType}, eventType==""}},
{"$or", bson.D{{"tags", bson.D{{"$in", tags}}}, tags==[]}},
{"$or",
bson.A{
bson.D{{"title", primitive.Regex{Pattern: ".*" + query + ".*", Options: "i"}}},
bson.D{{"description", primitive.Regex{Pattern: ".*" + query + ".*", Options: "i"}}},
}},
})
And my variables are extracted this way:
vars := request.URL.Query()
query := vars.Get("q")
eventType := vars.Get("type")
tags := strings.Split(vars.Get("tags"), ",")