複合演算子
Overview
このガイドでは、複合操作の実行方法を学習できます。
複合操作は、読み取り操作と書込み (write) 操作を 1 つの操作に結合します。 読み取り操作と書込み操作を個別に実行すると、両方の操作の間に他のユーザーがドキュメントを変更する可能性があります。 MongoDB は、複合操作の実行中に変更されたドキュメントに書込みロック (write lock) を適用することで、これを防ぎます。
MongoDB は次の複合操作をサポートしています。
Tip
複数のドキュメントの読み取りと書き込みが必要な場合は、トランザクション を使用します。
サンプル データ
次のスニペットを実行して、ドキュメントを tea.ratings
コレクションに読み込みます。
coll := client.Database("tea").Collection("ratings") docs := []interface{}{ bson.D{{"type", "Masala"}, {"rating", 10}}, bson.D{{"type", "Assam"}, {"rating", 5}}, bson.D{{"type", "Oolong"}, {"rating", 7}}, bson.D{{"type", "Earl Grey"}, {"rating", 8}}, bson.D{{"type", "English Breakfast"}, {"rating", 5}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
存在しないデータベースとコレクション
書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。
各ドキュメントには、 フィールドとtype
rating
フィールドに対応するお茶の種類の評価が含まれています。
注意
各例ではObjectID
値が切り捨てられます。この値はドライバーが個別に生成するためです。
検索と削除
FindOneAndDelete()
メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索し、そのドキュメントを削除します。 このメソッドは、削除されたドキュメントを含むSingleResult
を返します。
注意
このメソッドはDeleteOne()
メソッドとは異なります。 FindOneAndDelete()
は検索と削除を単一の操作として実行し、両方の操作の間にドキュメントが変更される可能性を排除します。
動作の変更
FineOneAndDeleteOptions
を渡すことで、 FindOneAndDelete()
メソッドの動作を変更できます。 FineOneAndDeleteOptions
を指定しない場合、ドライバーは各オプションのデフォルト値を使用します。
FineOneAndDeleteOptions
タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
---|---|
SetCollation() | The type of language collation to use when sorting results. Default: nil |
SetMaxTime() | The maximum amount of time that the query can run on the server. Default: nil |
SetProjection() | The fields to include in the document returned. Default: nil |
SetSort() | The sort fields and directions to order the documents matched. Default: nil |
SetHint() | The index to use to scan for documents. Default: nil |
例
次の例では、 FindOneAndDelete()
メソッドで、 type
が「Assamp」であるドキュメントを照合して削除します。
filter := bson.D{{"type", "Assam"}} var deletedDoc bson.D err := coll.FindOneAndDelete(context.TODO(), filter).Decode(&deletedDoc) if err != nil { panic(err) } fmt.Println(deletedDoc)
検索と更新
FindOneAndUpdate()
メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索し、更新ドキュメントに従って更新します。 このメソッドは一致したドキュメントを含むSingleResult
を返します。
注意
このメソッドはUpdateOne()
メソッドとは異なります。 FindOneAndUpdate()
は検索とアップデートを単一の操作として実行し、両方の操作の間にドキュメントが変更される可能性を排除します。
動作の変更
FineOneAndUpdateOptions
を渡すことで、 FindOneAndUpdate()
メソッドの動作を変更できます。 FineOneAndUpdateOptions
を指定しない場合、ドライバーは各オプションのデフォルト値を使用します。
FineOneAndUpdateOptions
タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
---|---|
SetArrayFilters() | The array elements the update applies to. Default: nil |
SetBypassDocumentValidation() | Whether to allow the write operation to opt-out of document level validation. Default: false |
SetCollation() | The type of language collation to use when sorting results. Default: nil |
SetMaxTime() | The maximum amount of time that the query can run on the server. Default: nil |
SetProjection() | The fields to include in the document returned. Default: nil |
SetReturnDocument() | Whether to return the original or updated document in the SingleResult .Default: options.Before |
SetSort() | The sort fields and directions to order the documents matched. Default: nil |
SetUpsert() | Whether to insert a new document if the query filter doesn't match any documents. Default: false |
SetHint() | The index to use to scan for documents. Default: nil |
例
次の例では、 FindOneAndUpdate()
メソッドを使用して、次のアクションを順番に実行します。
type
が「Oolong」であるドキュメントに一致します一致したドキュメントの
rating
を9
にアップデートします更新されたドキュメントを返します
filter := bson.D{{"type", "Oolong"}} update := bson.D{{"$set", bson.D{{"rating", 9}}}} opts := options.FindOneAndUpdate().SetReturnDocument(options.After) var updatedDoc bson.D err := coll.FindOneAndUpdate(context.TODO(), filter, update, opts).Decode(&updatedDoc) if err != nil { panic(err) } fmt.Println(updatedDoc)
検索と置換
FindOneAndReplace()
メソッドは、指定されたクエリフィルターに一致する最初のドキュメントを検索し、それを置換ドキュメントに置き換えます。 このメソッドは一致したドキュメントを含むSingleResult
を返します。
注意
このメソッドはReplaceOne()
メソッドとは異なります。 FindOneAndReplace()
は検索と置換を単一の操作として実行し、両方の操作の間にドキュメントが変更される可能性を排除します。
動作の変更
FineOneAndReplaceOptions
を渡すことで、 FindOneAndReplace()
メソッドの動作を変更できます。 FineOneAndReplaceOptions
を指定しない場合、ドライバーは各オプションのデフォルト値を使用します。
FineOneAndReplaceOptions
タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
---|---|
SetBypassDocumentValidation() | Whether to allow the write operation to opt-out of document level validation. Default: false |
SetCollation() | The type of language collation to use when sorting results. Default: nil |
SetMaxTime() | The maximum amount of time that the query can run on the server. Default: nil |
SetProjection() | The fields to include in the document returned. Default: nil |
SetReturnDocument() | Whether to return the original or replaced document in the SingleResult .Default: nil |
SetSort() | The sort fields and directions to order the documents matched. Default: nil |
SetUpsert() | Whether to insert a new document if the query filter doesn't match any documents. Default: false |
SetHint() | The index to use to scan for documents. Default: nil |
例
次の例では、 FindOneAndReplace()
メソッドを使用して、次のアクションを順番に実行します。
type
が「englishbreaker」であるドキュメントに一致します一致したドキュメントを、
type
が "Cylong" で、rating
が6
の新しいドキュメントを置き換えます
filter := bson.D{{"type", "English Breakfast"}} replacement := bson.D{{"type", "Ceylon"}, {"rating", 6}} var previousDoc bson.D err := coll.FindOneAndReplace(context.TODO(), filter, replacement).Decode(&previousDoc) if err != nil { panic(err) } fmt.Println(previousDoc)
詳細情報
上記の操作の実行方法の詳細については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。