Docs Menu

ドキュメントの更新

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

注意

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

Tip

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

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

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

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

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

// Creates a filter for all documents with a "name" of "Bagels N Buns"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
// Creates instructions to update the "name" field of the first document
// that matches the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
// 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 オブジェクトを返します。

ドキュメントの更新について詳しくは、「Update One」ガイドを参照してください。

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