LoginSignup
1
0

More than 3 years have passed since last update.

mongo-go-driverでBulkUpdateの実装

Posted at

概要

RDBにはだいたいBulkUpdate(一括更新)の機能があるのですが、MongoDBにおいてもその機能が用意されています。こちらのドキュメントにある通り、更新系のクエリをまとめて実行できます。
今回はGolangでupdateのクエリをBulk形式で実行する例を紹介します。

対応

Golang. MongoDB bulkWrite() to update slice of documentsの記事にある通り、mongo-go-driverのcollectionにBulkWriteのメソッドが用意されています。BulkWriteの引数に、mongo.WriteModelの配列に定義したクエリを設定して実行します。

実装サンプル

例題として、更新対象の_idと更新後のstatusを保持したstructの配列をbulk実行します。なお、コレクションオブジェクトを取得するための接続の実装は割愛します。

sampleBulkUpdate.go
func SetStatusPosts(request []postModel.PostStatusUpdateRequest) error {
    var operations []mongo.WriteModel
    // 受け取った配列の数分、updateのクエリオブジェクトを作成
    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)
    // BulkUpdateの実行。なお、collectionの取得処理は割愛・・・。
    _, err := collection.BulkWrite(context.Background(), operations, &bulkOption)
    if err != nil {
        return nil, err
    }
    return err
}

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0