Update/Replace mongodb document using struct & mongodb/mongo-go-driver

You should provide an update statement instead of a document as third parameter to the Collection.UpdateOne method. For example:

update := bson.NewDocument(
    bson.EC.SubDocumentFromElements(
        "$set",
        bson.EC.Double("pi", 3.14159),
    ),
)
collection.UpdateOne(ctx, filter, update)

See more on the available update operators in the MongoDB docs (the keys begin with '$').


I believe the accepted answer did not work for me because I am using the go.mongodb.org/mongo-driver package. With this package, the syntax is even simpler:

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

collection.UpdateOne(ctx, filter, update)