Mongodb如何通过正则表达式或多个字段进行搜索?

huangapple go评论70阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年6月28日 10:15:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/72780053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定