Overview
En esta guía, puedes aprender cómo usar el controlador MongoDB .NET/C# para realizar transacciones. Transacciones le permiten ejecutar una serie de operaciones que no cambian ningún dato hasta que la transacción es confirmada. Si alguna operación en la transacción devuelve un error, el driver cancela la transacción y descarta todos los cambios de datos antes de que sean visibles.
En MongoDB, las transacciones se ejecutan dentro de sesiones lógicas. Una sesión es un agrupamiento de operaciones de lectura o escritura relacionadas que usted planea ejecutar secuencialmente. Las sesiones habilitan la coherencia causal para un conjunto de operaciones o te permiten ejecutar operaciones en una ACID transaction. MongoDB garantiza que los datos involucrados en sus operaciones de transacción permanezcan coherentes, incluso si las operaciones encuentran errores inesperados.
Al usar el Driver .NET/C#, puedes crear una nueva sesión a partir de un
MongoClient instancia como un tipo IClientSession. Recomendamos reutilizar su cliente para múltiples sesiones y transacciones en lugar de crear una nueva instancia de cliente cada vez.
Advertencia
Utiliza un IClientSession únicamente con el MongoClient (o el MongoDatabase o MongoCollection asociado) que lo haya creado. El uso de un IClientSession con un MongoClient diferente provoca errores de operación.
Métodos
Cree un IClientSession utilizando el método síncrono StartSession() o el método asíncrono StartSessionAsync() en su instancia MongoClient. A continuación, puedes modificar el estado de la sesión utilizando el método set proporcionado por la interfaz IClientSession. Seleccione entre lo siguiente
Synchronous Methods y Asynchronous Methods pestañas para aprender sobre los métodos para gestionar tu transacción:
Método | Descripción |
|---|---|
| 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) |
| 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 |
| 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 |
| 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. IMPORTANTE: Al capturar excepciones dentro de la función de retorno utilizada por Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationTokenReturn Type: Task <TResult> |
Método | Descripción |
|---|---|
| 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) |
| 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: CancellationTokenReturn Type: Task |
| 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: CancellationTokenReturn Type: Task |
| 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. IMPORTANTE: Al capturar excepciones dentro de la función de retorno utilizada por Parameters: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationTokenReturn Type: Task <TResult> |
Opciones de transacción
Para configurar una transacción individual, pase una instancia de TransactionOptions al método StartTransaction() o WithTransaction(). El ejemplo de esta sección establece el nivel de consistencia de lectura en ReadConcern.Majority y el nivel de confirmación de escritura (write concern) en WriteConcern.WMajority.
Puede configurar un objeto TransactionOptions con las siguientes propiedades:
Propiedad | Descripción |
|---|---|
| Maximum amount of time that a single
commitTransaction command can run. If the commit exceeds
this limit, MongoDB Server returns a MaxTimeMSExpired
error and does not commit the transaction.If you omit this property, MongoDB Server applies the
default transaction runtime limit. Data Type: TimeSpan? |
| Read concern for the transaction. To learn more, see
Read Concern in the MongoDB Server
manual. Data Type: ReadConcern |
| Read preference for the transaction. To learn more, see
Read Preference in the
MongoDB Server manual. Data Type: ReadPreference |
| Write concern for the transaction. To learn more, see
Write Concern in the MongoDB Server
manual. Data Type: WriteConcern |
Ejemplo
Este ejemplo muestra cómo puede crear una sesión, configurar opciones de transacción, crear una transacción e insertar documentos en varias colecciones dentro de la transacción mediante los siguientes pasos:
Cree una sesión desde el cliente usando el método
StartSession().Cree un objeto
TransactionOptionspara configurar la transacción.Utiliza el método
StartTransaction()para iniciar una transacción.Inserte documentos en las colecciones
booksyfilms.Confirme la transacción usando el método
CommitTransaction().
var books = database.GetCollection<Book>("books"); var films = database.GetCollection<Film>("films"); // Begins transaction using (var session = mongoClient.StartSession()) { // Configures transaction options var transactionOptions = new TransactionOptions( readConcern: ReadConcern.Majority, writeConcern: WriteConcern.WMajority ); session.StartTransaction(transactionOptions); 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!
Nota
Operaciones paralelas no admitidas
El driver .NET/C# no admite la ejecución de operaciones paralelas dentro de una sola transacción.
Información Adicional
Para **aprender** más sobre los conceptos mencionados en esta **guía**, consulta las siguientes páginas en el manual del **servidor**:
Documentación de la API
Para aprender más sobre cualquiera de los tipos o métodos discutidos en esta guía, consulta la siguiente documentación de la API: