Docs Menu
Docs Home
/ / /
Go Driver
/ / /

一括操作

このガイドでは、 MongoDB Go Driver を使用して 一括操作 を実行する方法を学習できます。一括操作では、単一のメソッドで複数の書込み (write) 操作を実行することで、サーバーへの呼び出し回数を減らします。

Collection クラスと Client クラスはどちらも BulkWrite() メソッドを提供します。 Collection.BulkWrite() メソッドを使用して、単一のコレクションに対して複数の書込み操作を実行できます。 Client.BulkWrite() メソッドを使用して、複数の名前空間で一括書込みを実行できます。 MongoDBでは、名前空間 はデータベース名とコレクション名で構成されています。

重要

クライアント一括書き込みサーバーの要件

Clientインスタンスで一括操作を実行するには、アプリケーションがMongoDB Server v8.0 以降に接続されていることを確認します。

このガイドの例では、次の 構造体を使用します。

  • Book 構造体。これは、 db.booksコレクション内のドキュメントをモデル化します。各ドキュメントには、タイトル、著者、ページ長を含む書籍の説明が含まれています。

  • Poem 構造体。これは、 db.poemsコレクション内のドキュメントをモデル化します。各ドキュメントには、タイトル、著者、出版年を含むバージョンの説明が含まれています。

type Book struct {
Title string
Author string
Length int32
}
type Poem struct {
Title string
Author string
Year int32
}

このガイドの例を実行するには、次のスニペットを使用してサンプルデータを books コレクションと poemsコレクションにロードします。

bookColl := client.Database("db").Collection("books")
poemColl := client.Database("db").Collection("poems")
books := []interface{}{
Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331},
Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103},
}
poems := []interface{}{
Poem{Title: "Song of Myself", Author: "Walt Whitman", Year: 1855},
Poem{Title: "The Raincoat", Author: "Ada Limon", Year: 2018},
}
bookInsert, err := bookColl.InsertMany(context.TODO(), books)
poemInsert, err := poemColl.InsertMany(context.TODO(), poems)

Tip

存在しないデータベースとコレクション

書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。

単一の名前空間に対して一括操作を実行するには、コレクションで BulkWrite() メソッドを呼び出し、WriteModel ドキュメントの配列をパラメーターとして渡します。

1 つの名前空間に対する一括操作の書込み操作を定義するには、挿入、置換、更新、または削除ごとに WriteModel を作成します。

一括書き込みの挿入操作を定義するには、挿入するドキュメントを指定する InsertOneModel を作成します。複数のドキュメントを挿入するには、挿入するドキュメントごとに InsertOneModel を作成します。

次の方法を使用して、InsertOneModel の動作を指定できます。

方式
説明

SetDocument()

The document to insert.

次の例では、2 つの InsertOneModel インスタンスを作成して、2 つのドキュメントを booksコレクションに挿入します。

models := []mongo.WriteModel{
mongo.NewInsertOneModel().SetDocument(Book{Title: "Beloved", Author: "Toni Morrison", Length: 324}),
mongo.NewInsertOneModel().SetDocument(Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}),
}

一括書き込みの置換操作を定義するには、置換するドキュメントと 置換ドキュメントを指定する ReplaceOneModel を作成します。複数のドキュメントを置き換えるには、置き換えるドキュメントごとに ReplaceOneModel を作成します。

ReplaceOneModel の動作を指定するには、次の方法を使用します。

方式
説明

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to replace.

SetHint()

The index to use to scan for documents.

SetReplacement()

The document to replace the matched document with.

SetSort()

The sort order for matching documents. The replace operation replaces only the first document according to the sort criteria.

SetUpsert()

Whether to insert a new document if the query filter doesn't match any documents.

次の例では、title の値が "Lucy" である booksコレクション内のドキュメントを置き換えるために ReplaceOneModel を作成します。

models := []mongo.WriteModel{
mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "Lucy"}}).
SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473}),
}

一括書き込みの更新操作を定義するには、更新するドキュメントを指定するUpdateOneModel 更新ドキュメントを作成します。複数のドキュメントを更新するには、UpdateManyModel を使用します。

次の方法を使用して、各更新モデルの動作を指定できます。

方式
説明

SetArrayFilters()

The array elements the update applies to.

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to update.

SetHint()

The index to use to scan for documents.

SetSort()

The criteria to use when ordering matching documents. This method is only available for the UpdateOneModel class.

SetUpdate()

The modifications to apply on the matched documents.

SetUpsert()

Whether to insert a new document if the query filter doesn't match any documents.

次の例では、UpdateOneModel を作成して booksコレクション内のドキュメントを更新し、author"Elena Ferrante" の場合、ドキュメントの length15 ずつ減算します。

models := []mongo.WriteModel{
mongo.NewUpdateOneModel().SetFilter(bson.D{{"author", "Elena Ferrante"}}).
SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}}),
}

一括書き込みの削除操作を定義するには、削除するドキュメントを指定して DeleteOneModel を作成します。複数のドキュメントを削除するには、DeleteManyModel を使用します。

各削除モデルの動作を指定するには、次の方法を使用します。

方式
説明

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to delete.

SetHint()

The index to use to scan for documents.

次の例では、length300 より大きい booksコレクション内のドキュメントを削除するために DeleteManyModel を作成します。

models := []mongo.WriteModel{
mongo.NewDeleteManyModel().SetFilter(bson.D{{"length", bson.D{{"$gt", 300}}}}),
}

一括書き込み操作の動作を変更するには、BulkWriteOptionsインスタンスを BulkWrite() メソッドに渡します。

BulkWriteOptions タイプでは、以下の方法を使用してオプションを設定できます。

方式
説明

SetBypassDocumentValidation()

Specifies whether the operation can opt-out of document level validation.
Default: false

SetComment()

Specifies a comment to attach to the operation.
Default: nil

SetLet()

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let field for the delete and update commands in the MongoDB Server manual.
Default: nil

SetOrdered()

Specifies whether the driver stops performing write operations after an error occurs.
Default: true

BulkWrite() メソッドからは、 一括操作に関する情報を含む BulkWriteResult タイプが返されます。

BulkWriteResult 型には次のプロパティが含まれています。

プロパティ
説明

InsertedCount

挿入されたドキュメントの数。

MatchedCount

アップデート操作と置換操作でクエリフィルターに一致したドキュメントの数。

ModifiedCount

更新操作と置換操作によって変更されたドキュメントの数。

DeletedCount

削除されたドキュメントの数。

UpsertedCount

更新操作と置換操作によってアップサートされたドキュメントの数。

UpsertedIDs

アップサートされたドキュメントの_idへの操作インデックスのマッピング。

Acknowledged

書込み (write)操作が確認されたかどうかを示すブール値値。

一括書き込みで操作が順番に実行されるかどうかを指定するには、Ordered オプションをブール値値に設定します。このオプションを設定するには、BulkWriteOptionsインスタンスの Orderedフィールドを指定します。

デフォルトでは 、BulkWrite() メソッドは一括操作を追加した順序で実行し、エラーが発生した場合は停止します。

Tip

これは、次のコードに示すように、true の値を SetOrdered() メソッドに渡すことと同じです。

opts := options.BulkWrite().SetOrdered(true)

一括書き込み操作を任意の順序で実行し、エラーが発生した場合に続行するには、false の値を SetOrdered() メソッドに渡します。メソッドは、操作完了後にエラーを報告します。

次の例では、次のアクションを任意の順序で実行します。

  • 2 つのドキュメントを挿入します

  • title が「My Billian MongoDB」であるドキュメントを新しいドキュメントに置き換えます

  • 現在の length 値が 200 より小さい場合、すべてのドキュメントの length10 ずつ増加させます。

  • authorフィールド値に "Jam" が含まれるすべてのドキュメントを削除します

models := []mongo.WriteModel{
mongo.NewInsertOneModel().SetDocument(Book{Title: "Middlemarch", Author: "George Eliot", Length: 904}),
mongo.NewInsertOneModel().SetDocument(Book{Title: "Pale Fire", Author: "Vladimir Nabokov", Length: 246}),
mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "My Brilliant Friend"}}).
SetReplacement(Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}),
mongo.NewUpdateManyModel().SetFilter(bson.D{{"length", bson.D{{"$lt", 200}}}}).
SetUpdate(bson.D{{"$inc", bson.D{{"length", 10}}}}),
mongo.NewDeleteManyModel().SetFilter(bson.D{{"author", bson.D{{"$regex", "Jam"}}}}),
}
// Specifies that the bulk write is unordered
opts := options.BulkWrite().SetOrdered(false)
// Runs the bulk write operation and prints a summary of the
// data changes
results, err := bookColl.BulkWrite(context.TODO(), models, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", results.InsertedCount)
fmt.Printf("Number of documents replaced or updated: %d\n", results.ModifiedCount)
fmt.Printf("Number of documents deleted: %d\n", results.DeletedCount)
Number of documents inserted: 2
Number of documents replaced or updated: 2
Number of documents deleted: 1

一括操作後に次のドキュメントがbooksコレクションに存在します。

{"title":"Atonement","author":"Ian McEwan","length":351}
{"title":"Middlemarch","author":"George Eliot","length":904}
{"title":"Pale Fire","author":"Vladimir Nabokov","length":246}

複数の名前空間で一括操作を実行するには、クライアントで BulkWrite() メソッドを呼び出し、ClientWriteModel ドキュメントの配列をパラメーターとして渡します。

複数の名前空間に対する一括操作の書込み操作を指定するには、挿入、置換、更新、または削除ごとに ClientWriteModel を作成します。次のコードに示すように、各書き込みモデルを ClientBulkWrite 構造体に渡し、ターゲットのデータベースとコレクションを指定します。

writes := []mongo.ClientBulkWrite{
{"<database name>", "<collection name>", <write model>},
...
}

一括書き込みの挿入操作を定義するには、挿入するドキュメントを指定する ClientInsertOneModel を作成します。複数のドキュメントを挿入するには、挿入するドキュメントごとに ClientInsertOneModel を作成します。

次の方法を使用して、ClientInsertOneModel の動作を指定できます。

方式
説明

SetDocument()

The document to insert.

次の例では、2 つの ClientInsertOneModel インスタンスを作成し、1 つのドキュメントをbooksコレクションに挿入し、2 つのドキュメントをpoemsコレクションに挿入します。

bookInsertDoc := Book{Title: "Parable of the Sower", Author: "Octavia E. Butler", Length: 320}
poemInsertDoc := Poem{Title: "Fame is a fickle food", Author: "Emily Dickinson", Year: 1659}
writes := []mongo.ClientBulkWrite{
{"db", "books", mongo.NewClientInsertOneModel().SetDocument(bookInsertDoc)},
{"db", "poems", mongo.NewClientInsertOneModel().SetDocument(poemInsertDoc)},
}

一括書き込みの置換操作を定義するには、置換するドキュメントを指定するClientReplaceOneModel と置換ドキュメントを作成します。複数のドキュメントを置き換えるには、置き換えるドキュメントごとにClientReplaceOneModel を作成します。

ClientReplaceOneModel の動作を指定するには、次の方法を使用します。

方式
説明

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to replace.

SetHint()

The index to use to scan for documents.

SetReplacement()

The document to replace the matched document with.

SetSort()

The sort order for matching documents. The replace operation replaces only the first document according to the sort criteria.

SetUpsert()

Whether to insert a new document if the query filter doesn't match any documents.

この例では、次の操作を定義するための ClientReplaceOneModel インスタンスを作成しています。

  • title 値が "Lucy" であるドキュメントを置き換えるには、booksコレクションの操作を置き換えます

  • title 値が "Song of Myself" であるドキュメントを置き換えるには、poemsコレクションの操作を置き換えます

writes := []mongo.ClientBulkWrite{
{"db", "books", mongo.NewClientReplaceOneModel().
SetFilter(bson.D{{"title", "Lucy"}}).
SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473})},
{"db", "poems", mongo.NewClientReplaceOneModel().
SetFilter(bson.D{{"title", "Song of Myself"}}).
SetReplacement(Poem{Title: "America", Author: "Walt Whitman", Year: 1888})},
}

一括書き込みの更新操作を定義するには、更新するドキュメントを指定するClientUpdateOneModel 更新ドキュメントを作成します。複数のドキュメントを更新するには、 を使用します。ClientUpdateManyModel

次の方法を使用して、各更新モデルの動作を指定できます。

方式
説明

SetArrayFilters()

The array elements the update applies to.

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to update.

SetHint()

The index to use to scan for documents.

SetSort()

The criteria to use when ordering matching documents. This method is only available for the ClientUpdateOneModel class.

SetUpdate()

The modifications to apply on the matched documents.

SetUpsert()

Whether to insert a new document if the query filter doesn't match any documents.

この例では、次の操作を定義するための ClientUpdateOneModel インスタンスを作成しています。

  • booksコレクションに対する更新操作は、author 値が "Elena Ferrante" であるドキュメントを更新します

  • poemsコレクションに対する更新操作は、author 値が "Ada Limon" であるドキュメントを更新します

writes := []mongo.ClientBulkWrite{
{"db", "books", mongo.NewClientUpdateOneModel().
SetFilter(bson.D{{"author", "Elena Ferrante"}}).
SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}})},
{"db", "poems", mongo.NewClientUpdateOneModel().
SetFilter(bson.D{{"author", "Ada Limon"}}).
SetUpdate(bson.D{{"author", "Ada Limón"}})},
}

注意

前述の例の authorフィールドクエリフィルターに一致するすべてのドキュメントを更新するには、ClientUpdateManyModel インスタンスを使用します。

一括書き込みの削除操作を定義するには、削除するドキュメントを指定して ClientDeleteOneModel を作成します。複数のドキュメントを削除するには、ClientDeleteManyModel を使用します。

各削除モデルの動作を指定するには、次の方法を使用します。

方式
説明

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to delete.

SetHint()

The index to use to scan for documents.

この例では、次の操作を定義するための ClientDeleteOneModel インスタンスを作成しています。

  • booksコレクションに対する削除操作は、length 値が 103 であるドキュメントを削除します

  • poemsコレクションに対する削除操作は、year 値が 1855 であるドキュメントを削除します

writes := []mongo.ClientBulkWrite{
{"db", "books", mongo.NewClientDeleteOneModel().
SetFilter(bson.D{{"length", 103}})},
{"db", "poems", mongo.NewClientDeleteOneModel().
SetFilter(bson.D{{"year", 1855}})},
}

一括書き込み操作の動作を変更するには、ClientBulkWriteOptionsインスタンスを BulkWrite() メソッドに渡します。

ClientBulkWriteOptions タイプでは、以下の方法を使用してオプションを設定できます。

方式
説明

SetBypassDocumentValidation()

Specifies whether the operation can opt-out of document level validation.
Default: false

SetOrdered()

Specifies whether the driver stops performing write operations after an error occurs.
Default: true

SetComment()

Specifies a comment to attach to the operation.
Default: nil

SetLet()

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let field for the delete and update commands in the MongoDB Server manual.
Default: nil

SetWriteConcern()

Specifies the write concern for the operations.
Default: nil

SetVerboseResults()

Specifies whether detailed information about each successful operation is included in the result.
Default: false

BulkWrite() メソッドからは、 一括操作に関する情報を含む ClientBulkWriteResult タイプが返されます。

ClientBulkWriteResult 型には次のプロパティが含まれています。

プロパティ
説明

InsertedCount

挿入されたドキュメントの数。

MatchedCount

アップデート操作と置換操作でクエリフィルターに一致したドキュメントの数。

ModifiedCount

更新操作と置換操作によって変更されたドキュメントの数。

DeletedCount

削除されたドキュメントの数。

UpsertedCount

更新操作と置換操作によってアップサートされたドキュメントの数。

InsertResults

挿入された各ドキュメントの _id 値への操作インデックスのマップ。

UpdateResults

アップデートされた各ドキュメントの _id 値への操作インデックスのマップ。

DeleteResults

各削除されたドキュメントの _id 値への操作インデックスのマップ。

Acknowledged

書込み (write)操作が確認されたかどうかを示すブール値値。

HasVerboseResults

結果に詳細な結果が含まれているかどうかを示すブール値値。

一括書き込みで操作が順番に実行されるかどうかを指定するには、Ordered オプションをブール値値に設定します。このオプションを設定するには、ClientBulkWriteOptionsインスタンスの Orderedフィールドを指定します。

デフォルトでは、 BulkWrite()メソッドは一括操作を追加した順序で実行され、エラーが発生した場合は停止します。

Tip

これは、次のコードに示すように、true の値を SetOrdered() メソッドに渡すことと同じです。

opts := options.ClientBulkWrite().SetOrdered(true)

一括書き込み操作を任意の順序で実行し、エラーが発生した場合に続行するには、false の値を SetOrdered() メソッドに渡します。メソッドは、操作完了後にエラーを報告します。

次の例では、次のアクションを任意の順序で実行します。

  • 新しいドキュメントを books コレクションと poems コレクションに挿入します

  • poemsコレクション内の title 値が "The Raincoat" であるドキュメントを更新します。

  • booksコレクション内の title 値が "My Brilliant Friend" であるドキュメントを置き換えます

writes := []mongo.ClientBulkWrite{
{"db", "books", mongo.NewClientInsertOneModel().
SetDocument(Book{Title: "Middlemarch", Author: "George Eliot", Length: 904})},
{"db", "poems", mongo.NewClientInsertOneModel().
SetDocument(Poem{Title: "Mad Girl's Love Song", Author: "Sylvia Plath", Year: 1953})},
{"db", "poems", mongo.NewClientUpdateOneModel().
SetFilter(bson.D{{"title", "The Raincoat"}}).
SetUpdate(bson.D{{"title", "The Conditional"}})},
{"db", "books", mongo.NewClientReplaceOneModel().
SetFilter(bson.D{{"title", "My Brilliant Friend"}}).
SetReplacement(Book{Title: "The Story of a New Name", Author: "Elena Ferrante", Length: 480})},
}
opts := options.ClientBulkWrite().SetOrdered(false)
results, err := client.BulkWrite(context.TODO(), writes, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", results.InsertedCount)
fmt.Printf("Number of documents replaced or updated: %d\n", results.ModifiedCount)
Number of documents inserted: 2
Number of documents replaced or updated: 2

一括操作の実行可能な例については、 「 一括操作の実行 」を参照してください。

上記の操作の実行方法の詳細については、次のガイドを参照してください。

コレクションの一括書き込みに使用されるメソッドまたはタイプの詳細については、次のAPIドキュメントを参照してください。

クライアント一括書き込みに使用されるメソッドまたはタイプの詳細については、次のAPIドキュメントを参照してください。

戻る

アップサート

項目一覧

  • Overview
  • サンプル データ
  • コレクションの一括書込み (write)
  • コレクション一括書込みモデルを定義する
  • コレクション レベルの動作の変更
  • コレクション レベルの戻り値
  • コレクションレベルの実行順序
  • クライアント一括書込み (write)
  • クライアント一括書込みモデルの定義
  • クライアントレベルの動作の変更
  • クライアントレベルの戻り値
  • クライアントレベルの実行順序
  • 詳細情報
  • 関連操作
  • API ドキュメント