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 en la colección restaurants que tienen un campo cuisine con el valor "Pizza". Después de la actualización, estos documentos tendrán un campo cuisine con un valor de "Pasta and breadsticks".
Selecciona 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 muestra.
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 ver un ejemplo completamente ejecutable de la UpdateMany() operación, consulta la muestra 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 cómo actualizar documentos, consulta el Guía Actualizar Varios.
Para obtener más información sobre el uso de constructores, consulte Operaciones con constructores.