Jay
Jay

Reputation: 85

Dynamically create MongoDB Pipeline in Golang

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.

Upvotes: 0

Views: 626

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51652

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

Upvotes: 1

Related Questions