コレクション オブジェクトでReplaceOne()同期メソッドまたはReplaceOneAsync()非同期メソッドを使用して、あるドキュメントを別のドキュメントで置き換えることができます。
例
次のコードは、 cuisineフィールドの値が「Pizza」である、 restaurantsコレクション内の最初のドキュメントを置き換えます。 置き換え後、このドキュメントには「 mongoのピザ」の値と、address フィールドと borough フィールドの新しい値を持つ name フィールドが含まれます。
AsynchronousSynchronous対応するコードを表示するには、 タブまたは タブを選択します。
// 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 filtervar oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant documentRestaurant 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 documentreturn await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);ReplaceOneAsync()操作の完全に実行可能な例については、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 filtervar oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant documentRestaurant 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 documentreturn _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);ReplaceOne()操作の完全に実行可能な例については、ReplaceOne コードサンプルを参照してください。
期待される結果
前述の例のいずれかを実行すると、次の結果が出力されます。
First pizza restaurant before replacement: J&V Famous PizzaRestaurants modified by replacement: 1First pizza restaurant after replacement: Mongo's PizzaResetting sample data...done.詳細情報
ドキュメントの置き換えの詳細については、 「ドキュメントの置き換え」 ガイドを参照してください。
ビルダの使用の詳細については、「 ビルダを使用した操作 」を参照してください。