Docs Menu
Docs Home
/ / /
C#/.NET
/

ドキュメントの置き換え

項目一覧

  • 期待される結果
  • 詳細情報
  • API ドキュメント

あるドキュメントを別のドキュメントで置き換えるには、コレクション オブジェクトで 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 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()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Asynchronously replaces the existing restaurant document with the new document
return 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 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()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);

ReplaceOne()操作の完全に実行可能な例については、 ReplaceOne コード サンプルを参照してください。

前述の例のいずれかを実行すると、次の結果が出力されます。

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.

ドキュメントの置き換えの詳細については、 置換操作のガイドを参照してください。

ビルダの使用の詳細については、「 ビルダを使用した操作 」を参照してください。

戻る

多くのドキュメントの更新