For your use case, you would use collection.BulkWrite
. You can find examples of how to use go-mongo-driver
in the examples directory of the repository.
collection.UpdateMany()
will update multiple documents in the collection using the same update filter and modifications. There is a lot more documentation in the docs of the mongo shell equivalent. Example:
result, err := coll.UpdateMany(
context.Background(),
bson.NewDocument(
bson.EC.SubDocumentFromElements("qty",
bson.EC.Int32("$lt", 50),
),
),
bson.NewDocument(
bson.EC.SubDocumentFromElements("$set",
bson.EC.String("size.uom", "cm"),
bson.EC.String("status", "P"),
),
bson.EC.SubDocumentFromElements("$currentDate",
bson.EC.Boolean("lastModified", true),
),
),
)
collection.BulkWrite()
will perform a set of bulk write operations. The BulkWrite API was only introduced a couple of days ago for the go driver. There are little examples, however you can always check the tests
files. Example:
var operations []mongo.WriteModel
operation := mongo.NewUpdateOneModel()
operation.Filter(bson.NewDocument(
bson.EC.SubDocumentFromElements("qty",
bson.EC.Int32("$lt", 50),
),
))
operation.Update(bson.NewDocument(
bson.EC.SubDocumentFromElements("$set",
bson.EC.String("size.uom", "cm"),
bson.EC.String("status", "P"),
),
bson.EC.SubDocumentFromElements("$currentDate",
bson.EC.Boolean("lastModified", true),
),
))
operations = append(operations, operation)
result, err := coll.BulkWrite(
context.Background(),
operations,
)