1

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'
Chau Loi
  • 1,106
  • 1
  • 14
  • 36

1 Answers1

2

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)
ashing
  • 131
  • 3
  • how to avoid case sensitive here ? – Chau Loi Jun 28 '22 at 16:13
  • 1
    add `'$options' : 'i'` to cond like `bson.M{"title": bson.M{"$regex": "input", "$options": "i"}}` for more, you can check this link: https://stackoverflow.com/questions/8246019/case-insensitive-search-in-mongo – ashing Jun 29 '22 at 01:54