Você pode atualizar mais de um documento usando o método UpdateMany() em um objeto de coleção.
Exemplo
O código a seguir atualiza todos os documentos na coleção restaurants que têm um campo cuisine com o valor de "Pizza". Após a atualização, esses documentos terão um campo cuisine com o valor de "Macarrão e pedaços de pão".
Selecione a aba Asynchronous ou Synchronous para ver o código correspondente.
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 filtervar 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 um exemplo completamente executável da operação UpdateManyAsync(), consulte a amostra 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 filtervar 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 um exemplo completamente executável da operação UpdateMany(), consulte a amostra de código UpdateMany.
Resultado esperado
A execução de qualquer um dos exemplos completos anteriores imprime os seguintes resultados:
Restaurants with cuisine "Pizza" found: 1163Restaurants modified by update: 1163Restaurants with cuisine "Pasta and breadsticks" found after update: 1163Resetting sample data...done.MAIS INFORMAÇÕES
Para saber mais sobre como atualizar documentos, consulte o guia Atualizar muitos .
Para saber mais sobre como usar construtores, consulte Operações com construtores.