Puedes actualizar más de un documento utilizando el método UpdateMany() 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 la pestaña Asynchronous o 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 un ejemplo completamente ejecutable de la operación UpdateManyAsync(), consulta la Muestra de código de 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 ver un ejemplo completamente ejecutable de la UpdateMany() operación, consulta la muestra de código UpdateMany.
Resultado esperado
Ejecutar cualquiera de los ejemplos completos anteriores imprime 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 la guía Actualizar muchos.
Para obtener más información sobre el uso de los desarrolladores, consulta Operaciones con Desarrolladores.