英文:
Mongodb how to search by regex OR on many fields?
问题
我想在mongodb的多个字段上进行搜索。
以下是我目前的做法:
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)
然而,它的工作方式是使用AND
,像这样:
WHERE title ~ 'input' AND author ~ 'input' AND content ~ 'input'
我希望它能像这样使用OR
:
WHERE title ~ 'input' OR author ~ 'input' OR content ~ 'input'
英文:
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'
答案1
得分: 2
也许你可以直接使用$or
和$regex
。
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论