英文:
Dynamically create MongoDB Pipeline in Golang
问题
大家好,
我正在使用MongoDB/Golang驱动程序,并且有以下的Golang代码来构建一个管道。我已经成功测试过了,它可以正常工作:
.
.
matchStage := bson.D{
{"$match", bson.D{
{"$or", bson.A{
bson.D{{"featureA", "string123"}},
bson.D{{"featureA", "string456"}},
bson.D{{"featureA", "string789"}},
bson.D{{"featureA", "string012"}},
}},
}},
}
filterCursor, err := collection.Aggregate(ctx, mongo.Pipeline{matchStage})
.
.
我的问题是,假设我将我的bson.D值作为一个切片输入,我如何动态构建这个查询?具体来说,我事先知道"featureA"的键,并且会得到一个切片输入:
features := []string{"string123", "string456", "string789", "string012"}
我知道这应该相对简单,但我已经为此苦苦思索了几个小时,尝试了循环遍历切片、JSON编组/解组等方法。
英文:
All,
I am using the MongoDB/Golang driver and have the following Golang code to build a pipeline. I've successfully tested this and it works:
.
.
matchStage := bson.D{
{"$match",bson.D{
{"$or", bson.A{
bson.D{{"featureA","string123"}},
bson.D{{"featureA","string456"}},
bson.D{{"featureA","string789"}},
bson.D{{"featureA","string012"}},
}},
}},
}
filterCursor, err := collection.Aggregate(ctx, mongo.Pipeline{matchStage})
.
.
My question is, assuming I'm getting my bson.D values as a slice input, how do I build this query dynamically?? Specifically, I know the key of "featureA" in advance and am fed an slice of:
features := []string{"string123", "string456", "string"789", "string012"}
I know this has to be relatively simple, but I've been cracking my head on this for hours now, looping through the slice, json marshaling/unmarshaling, etc.
答案1
得分: 1
你可以这样做:
featureExpr := bson.A{}
for _, f := range features {
featureExpr = append(featureExpr, bson.D{{"featureA", f}})
}
matchStage := bson.D{
{"$match", bson.D{{"$or", featureExpr}}},
}
英文:
You can do this:
featureExpr:=bson.A{}
for _,f:=range features {
featureExpr=append(featureExpr,bson.D{{"featureA",f}})
}
matchStage := bson.D{
{"$match",bson.D{{"$or", featureExpr}},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论