You can update a single document using the UpdateOne() method on a MongoCollection
object. This method requires a query filter, which specifies which document to update, and an update statement, which specifies the changes the driver should make to the first document matching the query filter.
注意
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」ガイドを参照してください。
ビルダの使用の詳細については、「 ビルダを使用した操作 」を参照してください。