Puede actualizar más de un documento utilizando el UpdateMany() método en un objeto de colección.
Ejemplo
El siguiente código actualiza todos los documentos de la colección restaurants que tienen un campo cuisine con el valor "Pizza". Tras la actualización, estos documentos tendrán un campo cuisine con el valor "Pasta y palitos de pan".
Seleccione el Asynchronous o la pestaña Synchronous para ver el código correspondiente.
const string oldValue = "Pizza"; const string newValue = "Pasta and breadsticks"; // Creates a filter for all documents with a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Cuisine, oldValue); // Creates instructions to update the "cuisine" field of documents that // match the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Cuisine, newValue); // Updates all documents that have a "cuisine" value of "Pizza" return await _restaurantsCollection.UpdateManyAsync(filter, update);
Para ver un ejemplo completamente ejecutable de la operación UpdateManyAsync(), consulte
Ejemplo de código UpdateManyAsync.
const string oldValue = "Pizza"; const string newValue = "Pasta and breadsticks"; // Creates a filter for all documents with a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Cuisine, oldValue); // Creates instructions to update the "cuisine" field of documents that // match the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Cuisine, newValue); // Updates all documents that have a "cuisine" value of "Pizza" return _restaurantsCollection.UpdateMany(filter, update);
Para obtener un ejemplo completamente ejecutable de la UpdateMany() operación, consulte el ejemplo de código UpdateMany.
Resultado esperado
Al ejecutar cualquiera de los ejemplos completos anteriores se imprimen los siguientes resultados:
Restaurants with cuisine "Pizza" found: 1163 Restaurants modified by update: 1163 Restaurants with cuisine "Pasta and breadsticks" found after update: 1163 Resetting sample data...done.
Más información
Para obtener más información sobre la actualización de documentos, consulte la Actualizar muchas guías.
Para obtener más información sobre el uso de constructores, consulte Operaciones con constructores.