Most RDBs have a Bulk Update feature, but MongoDB also has that feature. As you can see in the Documentation here, you can execute update queries all at once. This time, I will introduce an example of executing an update query in Bulk format in Golang.
As mentioned in the Golang. MongoDB bulkWrite () to update slice of documents article, the mongo-go-driver collection provides a method for BulkWrite. Set the query defined in the array of mongo.WriteModel in the argument of BulkWrite and execute it.
As an example, bulk execute an array of structs that holds the _id to be updated and the status after the update. The implementation of the connection to get the collection object is omitted.
sampleBulkUpdate.go
func SetStatusPosts(request []postModel.PostStatusUpdateRequest) error {
var operations []mongo.WriteModel
//Create a query object for update for the number of received arrays
for _, r := range request {
operation := mongo.NewUpdateOneModel()
operation.SetFilter(bson.D{{Key: "_id", Value: r.PostID}})
operation.SetUpdate(bson.D{{Key: "$set", Value: bson.D{{Key: "status", Value: r.Status}}}})
operation.SetUpsert(false)
operations = append(operations, operation)
}
bulkOption := options.BulkWriteOptions{}
bulkOption.SetOrdered(true)
//Execute Bulk Update. The collection acquisition process is omitted.
_, err := collection.BulkWrite(context.Background(), operations, &bulkOption)
if err != nil {
return nil, err
}
return err
}
Recommended Posts