Docs Menu

Docs HomeGo

複合演算子

項目一覧

  • 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」であるドキュメントに一致します

  • 一致したドキュメントのrating9にアップデートします

  • 更新されたドキュメントを返します

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" で、 rating6の新しいドキュメントを置き換えます

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 ドキュメントを参照してください。

←  一括操作コマンドの実行 →
フィードバックを送る
© 2022 MongoDB, Inc.

会社概要

© 2022 MongoDB, Inc.