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

ドキュメントの更新

項目一覧

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

UpdateOne() メソッド を使用して単一のドキュメントを更新MongoCollection オブジェクトのメソッド。このメソッドには、アップデートするドキュメントを指定するクエリフィルターと、クエリフィルターに一致する最初のドキュメントに対してドライバーが行う必要がある変更を指定するアップデートステートメントが必要です。

注意

UpdateOne() メソッドは、フィルターに一致する最初のドキュメントのみをアップデートします。複数のドキュメントをアップデートするには、 UpdateMany() メソッドを使用します。

Tip

UpdateOptions のインスタンスを渡すことができます UpdateOne()動作をカスタマイズするには、 メソッドを使用します。

次の例では、Builders を使用して、restaurants コレクション内の "Bagels N Buns" という名前の最初のドキュメントのname を "2 Bagels 2 Buns" にアップデートします。

AsynchronousSynchronous対応するコードを表示するには、 タブまたは タブを選択します。

const string oldValue = "Bagels N Buns";
const string newValue = "2 Bagels 2 Buns";
// Creates a filter for all documents with a "name" of "Bagels N Buns"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, oldValue);
// Creates instructions to update the "name" field of the first document
// that matches the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, newValue);
// Updates the first document that has a "name" value of "Bagels N Buns"
return await _restaurantsCollection.UpdateOneAsync(filter, update);

UpdateOneAsync()操作の完全に実行可能な例えについては、「UpdateOneAsync の例え」を参照してください。

const string oldValue = "Bagels N Buns";
const string newValue = "2 Bagels 2 Buns";
// Creates a filter for all documents with a "name" of "Bagels N Buns"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, oldValue);
// Creates instructions to update the "name" field of the first document
// that matches the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, newValue);
// Updates the first document that has a "name" value of "Bagels N Buns"
return _restaurantsCollection.UpdateOne(filter, update);

UpdateOneAsync()操作の完全に実行可能な例については、「UpdateOne の例え」を参照してください。

前述の例のいずれかを実行した後は、UpdateOne() を呼び出すたびに、コンソールに以下が書き込まれます。

Updated documents: 1

Tip

UpdateOne() UpdateResult を返す オブジェクト。

ドキュメントのアップデートについて詳しくは、「ドキュメントの修正」ガイドを参照してください。

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

戻る

複数のドキュメントの挿入