Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
C#/.NET ドライバー
/

トランザクション内のバッチ操作

このガイドでは、MongoDB .NET/C# ドライバーを使用してトランザクションを実行する方法を学習できます。 トランザクションを使用すると、トランザクションがコミットされるまでデータを変更しない一連の操作を実行できます。 トランザクション内のいずれかの操作でエラーが返された場合、ドライバーはトランザクションをキャンセルし、変更が反映される前にすべてのデータ変更を破棄します。

MongoDBは、トランザクション操作で予期せぬエラーが発生した場合でも、その操作に関わるデータの一貫性が保たれることを保証します。

MongoDBでは、トランザクションは論理セッション内で実行されます。セッションは、順番に実行されるよう関連付けられた読み取り操作または書き込み操作のグループです。セッションにより、一連の操作に対する 因果整合性 が有効になる、またはACID transaction 内で操作を実行できるようになります。

.NET/C# ドライバーを使用すると、 MongoClientインスタンスからIClientSession型の新しいセッションを作成できます。 毎回新しいクライアントをインスタンス化するのではなく、クライアントを複数のセッションやトランザクションで再利用することを推奨します。

次の例では、StartSession() メソッドを呼び出してセッションを作成する方法を示しています。

var client = new MongoClient("mongodb://localhost:27017");
var session = client.StartSession();

警告

IClientSessionは、それを作成したMongoClient (または関連付けられたMongoDatabaseまたはMongoCollection )でのみ使用します。 IClientSessionと別のMongoClientを使用すると、操作エラーが発生します。

セッションの動作をカスタマイズするには、ClientSessionOptionsクラスのインスタンスを StartSession() メソッドに渡します。次の表では、ClientSessionOptionsオブジェクトに設定できるプロパティを説明します。

プロパティ
説明

CausalConsistency

Specifies whether the session is causally consistent. In a causally consistent session, the driver executes operations in the order they were issued. To learn more, see Causal Consistency.

Data Type: boolean
Default: true

DefaultTransactionOptions

Specifies the default transaction options for the session. This includes the maximum commit time, read concern, read preference, and write concern.

Default: null

Snapshot

Specifies whether the driver performs snapshot reads. To learn more about snapshot reads, see Read Concern "snapshot" in the MongoDB Server manual.

Data Type: boolean
Default: false

次のコード例は、カスタム オプションを使用してセッションを作成する方法を示しています。

var client = new MongoClient("mongodb://localhost:27017");
var sessionOptions = new ClientSessionOptions
{
CausalConsistency = true,
DefaultTransactionOptions = new TransactionOptions(
readConcern: ReadConcern.Available,
writeConcern: WriteConcern.Acknowledged)
};
var session = client.StartSession(sessionOptions);

MongoDB は特定のクライアントセッションで因果整合性を有効にします。因果整合性モデルは、分散システム内でセッション内の操作が因果順序で実行されることを保証します。クライアントは、因果関係、または操作間の依存関係と整合性のある結果を観察します。例、ある操作が別の操作の結果に論理的に依存する一連の操作を実行すると、後続のすべての読み取りは 依存関係を反映します。

因果整合性を保証するには、クライアントセッションが次の要件を満たす必要があります。

  • セッションを開始するとき、ドライバーは 因果整合性 オプションを有効にする必要があります。このオプションはデフォルトで有効になっています。

  • 操作は 1 つのスレッド上の 1 つのセッションで実行する必要があります。それ以外の場合、セッションまたはスレッドは optime とクラスター時間の値を相互に通信する必要があります。 これらの値を通信する 2 つのセッションの例については、 MongoDB Serverマニュアルの 因果整合性の例 を参照してください。

  • ReadConcern.Majority の読み取り保証 (read concern)を使用する必要があります。

  • WriteConcern.WMajority の書込み保証 (write concern)を使用する必要があります。これは、デフォルトの書込み保証 (write concern)の値です。

次の表では、因果整合性のあるセッションが提供する保証について説明しています。

保証
説明

書込み操作の結果を読み取る

読み取り操作は、前の書込み操作の結果を反映します。

単調な読み取り

読み取り操作では、前の 読み取り操作よりも前のデータ状態を反映した結果は返されません。

単調書込み

書込み操作が他の書込み操作に優先する必要がある場合、サーバーはこの書込み操作を最初に実行します。

例、InsertOne() を呼び出してドキュメントを挿入し、UpdateOne() を呼び出して挿入されたドキュメント を変更すると、サーバーは最初に挿入操作を実行します。

書込み操作の前に読み取り操作をする

書込み操作が他の読み取り操作の後に続く必要がある場合、サーバーは最初に読み取り操作を実行します。

例、Find() を呼び出してドキュメントを取得し、DeleteOne() を呼び出して取得されたドキュメントを削除すると、サーバーは最初に検索操作を実行します。

Tip

このセクションで述べられた概念の詳細については、次のMongoDB Serverマニュアル エントリを参照してください。

IClientSessionインスタンスで同期StartSession() メソッドまたは非同期StartSessionAsync() メソッドのいずれかを使用してMongoClient を作成します。次に、 IClientSessionインターフェースが提供するメソッドセットを使用してセッション状態を変更します。 トランザクションを管理する方法については、次の Synchronous Methodsタブと タブから選択してください。Asynchronous Methods

方式
説明

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransaction()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken

CommitTransaction()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken

WithTransaction()

Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

重要: WithTransaction()で使用されるコールバック関数内で例外をキャッチする場合は、試行ブロックを終了する前に例外を再スローする必要があります。それに失敗すると、無限ループが発生する可能性があります。 この場合の例外の処理方法の詳細については、サーバー マニュアルの「C# トランザクション 」を参照し、例のを表示するには言語ドロップダウンから を選択します。


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: Task <TResult>
方式
説明

StartTransaction()

Starts a new transaction, configured with the given options, on this session. Throws an exception if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions (optional)

AbortTransactionAsync()

Ends the active transaction for this session. Throws an exception if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

CommitTransactionAsync()

Commits the active transaction for this session. Throws an exception if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

Parameter: CancellationToken
Return Type: Task

WithTransactionAsync()

Starts a transaction on this session and runs the given callback. To learn more about this method, see the withTransaction() page in the Server manual.

重要: WithTransactionAsync()で使用されるコールバック関数内で例外をキャッチする場合は、試行ブロックを終了する前に例外を再スローする必要があります。それに失敗すると、無限ループが発生する可能性があります。 この場合の例外の処理方法の詳細については、サーバー マニュアルの「C# トランザクション 」を参照し、例のを表示するには言語ドロップダウンから を選択します。


Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Return Type: Task <TResult>

この例では、次の手順でセッションを作成し、トランザクションを作成し、トランザクション内の複数のコレクションにドキュメントを挿入する方法を示しています。

  1. StartSession()メソッドを使用してクライアントからセッションを作成します。

  2. トランザクションを開始するには、 StartTransaction() メソッドを使用します。

  3. booksfilmsコレクションと コレクションにドキュメントを挿入します。

  4. CommitTransaction()メソッドを使用してトランザクションをコミットします。

var books = database.GetCollection<Book>("books");
var films = database.GetCollection<Film>("films");
// Begins transaction
using (var session = mongoClient.StartSession())
{
session.StartTransaction();
try
{
// Creates sample data
var book = new Book
{
Title = "Beloved",
Author = "Toni Morrison",
InStock = true
};
var film = new Film
{
Title = "Star Wars",
Director = "George Lucas",
InStock = true
};
// Inserts sample data
books.InsertOne(session, book);
films.InsertOne(session, film);
// Commits our transaction
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine("Error writing to MongoDB: " + e.Message);
return;
}
// Prints a success message if no error thrown
Console.WriteLine("Successfully committed transaction!");
}
Successfully committed transaction!

注意

並列操作はサポートされていません

.NET/ C#ドライバーは、単一のトランザクション内での並列操作の実行中をサポートしていません。

MongoDB Server v8.0 以降を使用している場合は、BulkWrite() メソッドまたは BulkWriteAsync() メソッドを使用して、1 つのトランザクション内で複数の名前空間に対して書込み操作を実行できます。 詳細については、「 一括書込み (write) 操作 」を参照してください。

このガイドで言及されている概念の詳細については、サーバー マニュアルの次のページを参照してください。

このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。

戻る

一括書き込み操作

項目一覧