Home > Net >  Mongodb how to search by regex OR on many fields?
Mongodb how to search by regex OR on many fields?

Time:06-29

I want to make a search on many fields of mongodb.

Here is what I did so far

var filter bson.D
filter = append(filter, bson.E{"title", primitive.Regex{Pattern: "input", Options: "i"}})
filter = append(filter, bson.E{"author", primitive.Regex{Pattern: "input", Options: "i"}})
filter = append(filter, bson.E{"content", primitive.Regex{Pattern: "input", Options: "i"}})
cur, err := p.postProposalCollection.Find(ctx, filter)

However it workds as AND like this

WHERE title ~ 'input' AND author ~ 'input' AND content ~ 'input'

I want it to work as OR like this

WHERE title ~ 'input' OR author ~ 'input' OR content ~ 'input'

CodePudding user response:

maybe you can use $or and $regex directly

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)
  • Related