Puede reemplazar un documento por otro utilizando el ReplaceOne() método sincrónico o el método asincrónico ReplaceOneAsync() en un objeto de colección.
Ejemplo
El siguiente código reemplaza el primer documento de la colección restaurants que tiene el valor "Pizza" en el campo cuisine. Tras el reemplazo, este documento tendrá un campo name con el valor "Mongo's Pizza" y nuevos valores para los campos address y borough.
Seleccione el Asynchronous o la pestaña Synchronous para ver el código correspondiente.
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);
Para ver un ejemplo completamente ejecutable de la operación ReplaceOneAsync(), consulte
Ejemplo de código ReplaceOneAsync.
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);
Para obtener un ejemplo completamente ejecutable de la ReplaceOne() operación, consulte el ejemplo de código ReplaceOne.
Resultado esperado
Al ejecutar cualquiera de los ejemplos completos anteriores se imprimen los siguientes resultados:
First pizza restaurant before replacement: J&V Famous Pizza Restaurants modified by replacement: 1 First pizza restaurant after replacement: Mongo's Pizza Resetting sample data...done.
Información Adicional
Para obtener más información sobre cómo reemplazar documentos, consulte la Guía dereemplazo de documentos.
Para obtener más información sobre el uso de constructores, consulte Operaciones con constructores.