Search code examples
gomongo-go

How to BulkWrite\UpdateMany with Go driver for MongoDB


I'm migrating from mgo driver, and my function looks like this:

queue := collection.Bulk()
for j := range changes {
    ..
    queue.Update(doc, update)
}
saveResult, err := queue.Run()

This makes some $push and $set updates to a single document in a loop. How should I do this with the official driver ? Is it collection.BulkWrite() or collection.UpdateMany() ? Documentation is so vague, I'm lost on how use them both and what's the difference. Any help would be appreciated.


Solution

  • 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,
    )