在Golang中动态创建MongoDB管道

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

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}},
}

huangapple
  • 本文由 发表于 2021年12月4日 03:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/70219616.html
匿名

发表评论

匿名网友

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

确定