How to assign a value to a field using $set in a go-driver?

I used Mongo version 4.2.3, go-driver version 1.9.1
I succeeded when I executed the command in the Mongo shell, but failed consistently when I used go-driver
Here are the commands I executed in the Mongo shell:

db.tbl. update({}, [{$set: {'labels_bak': '$labels'}}], {"multi": true})

Here’s The go code I’m writing:

update := bson.M{
	"$set": bson.M{
		"labels_bak":  "$labels",
	},
}

Hello @Hu_XiaoYu, welcome to the MongoDB Community forum!

You can try this code:

filter := bson.D{{}}
pipe := bson.D{{ "$set", bson.D{{ "labels_bak", "$labels"}} }}
updateResult, err := collection.UpdateMany(ctx, filter, mongo.Pipeline{ pipe })

Note the usage of the mongo.Pipeline when using the Updates with Aggregation Pipeline.

2 Likes

Thank you for your answer. It was very helpful to me!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.