Updater
The Updater() method is used to obtain a new generic updater object, namely Updater[T]. With the methods of Updater[T], we can execute relevant update operations.
Update a single document
go
updateResult, err := userColl.Updater().
Filter(query.Id("60e96214a21b1b0001c3d69e")).
Updates(update.Set("name", "Mingyong Chen")).
UpdateOne(context.Background())The
UpdateOnemethod is used to update a single document. TheupdateResultis of type*mongo.UpdateResult.Through the
Updatesmethod, we can specify the operations for the update. This method accepts parameters of typeany, allowing for any type of argument to be passed in, provided they conform to a valid update statement structure. In the example provided,update.Set("name", "Mingyong Chen")is used to specify that thenamefield should be updated to "Mingyong Chen". For more buildss of update statements, refer to theupdatepackage.
Update multiple documents
go
updateResult, err := userColl.Updater().
Updates(update.Set("name", "Mingyong Chen")).
UpdateMany(context.Background())- The
UpdateManymethod is used for updating multiple documents. TheupdateResultis of type*mongo.UpdateResult.
Upsert operation
go
updateResult, err := userColl.Updater().
Filter(query.Eq("name", "Mingyong Chen")).
Updates(update.NewBuilder().Set("name", "Mingyong Chen").Set("age", 18).Build()).
Upsert(context.Background())- The
Upsertmethod is used to update or insert a single document. TheupdateResultis of type*mongo.UpdateResult.