Go driver Use of undefined variable: this

Hey @chapad, thanks for the question! I think the issue may be related to using bson.E as the Value in another bson.E. Typically a bson.E should never be used as the Value in a bson.E because the generated BSON doesn’t have the expected structure.

For example, this part of your aggregation pipeline:

bson.D{bson.E{Key: "$set", Value: bson.E{
    Key: "product_types", Value: bson.E{
        Key: "$map", Value: bson.D{
            bson.E{Key: "input", Value: "$product_types"},
// ...

should be rewritten using a bson.D as the Values:

bson.D{
    bson.E{Key: "$set", Value: bson.D{
        bson.E{Key: "product_types", Value: bson.D{
            bson.E{Key: "$map", Value: bson.D{
                bson.E{Key: "input", Value: "$product_types"},
// ...

Recent versions of MongoDB Compass support exporting aggregation pipelines as Go-syntax BSON documents (see the aggregation Export to Language docs). That can be really helpful for translating complex aggregation pipelines that work in the MongoDB shell to Go-syntax aggregation pipelines. Check it out and see if it helps!

P.S. The top-level element for an “Export to Language” exported aggregation pipelines is a bson.A, but you can update that top-level bson.A to mongo.Pipeline to make it more readable.

3 Likes