Overview
En esta guía, puedes aprender a utilizar el controlador MongoDB .NET/C# para ejecutar transacciones. Las transacciones permiten ejecutar una serie de operaciones que no modifican ningún dato hasta que se confirme la transacción. Si alguna operación en la transacción devuelve un error, el controlador cancela la transacción y descarta todos los cambios de datos antes de que lleguen a ser 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.
Cuando uses el controlador .NET/C#, puedes crear una nueva sesión a partir de una instancia MongoClient como un tipo IClientSession. Recomendamos reutilizar tu cliente para múltiples sesiones y transacciones en lugar de instanciar un nuevo 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 usando el método StartSession() síncrono o StartSessionAsync() asíncrono en su instancia de MongoClient. Luego puedes modificar el estado de la sesión utilizando el método set proporcionado por la interfaz IClientSession. Selecciona una de las siguientes opciones en las pestañas Synchronous Methods y Asynchronous Methods para conocer los métodos de gestión de 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. |
| 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. |
| 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. |
| 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. IMPORTANT: When catching exceptions within the callback function used by
|
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. |
| 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. |
| 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. |
| 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. IMPORTANT: When catching exceptions within the callback function used by
|
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 |
| Read concern for the transaction. To learn more, see Read Concern in the MongoDB Server manual. |
| Read preference for the transaction. To learn more, see Read Preference in the MongoDB Server manual. |
| Write concern for the transaction. To learn more, see Write Concern in the MongoDB Server manual. |
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!"); }
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: