Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

Utiliza Transacciones en C#

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.

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

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.

IMPORTANT: When catching exceptions within the callback function used by WithTransaction(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


Parámetros: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Tipo de devolución: Task <TResult>

Método
Descripción

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.

IMPORTANT: When catching exceptions within the callback function used by WithTransactionAsync(), you must rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see Transactions in the Server manual and select C# from the language dropdown to view the example.


Parámetros: Func <IClientSessionHandle, CancellationToken, Task<TResult>>, TransactionOptions, CancellationToken
Tipo de devolución: Task <TResult>

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

MaxCommitTime

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?

ReadConcern

Read concern for the transaction. To learn more, see Read Concern in the MongoDB Server manual.

Data Type: ReadConcern

ReadPreference

Read preference for the transaction. To learn more, see Read Preference in the MongoDB Server manual.

Data Type: ReadPreference

WriteConcern

Write concern for the transaction. To learn more, see Write Concern in the MongoDB Server manual.

Data Type: WriteConcern

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:

  1. Cree una sesión desde el cliente usando el método StartSession().

  2. Cree un objeto TransactionOptions para configurar la transacción.

  3. Utiliza el método StartTransaction() para iniciar una transacción.

  4. Inserte documentos en las colecciones books y films.

  5. 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.

Para **aprender** más sobre los conceptos mencionados en esta **guía**, consulta las siguientes páginas en el manual del **servidor**:

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: