AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

ドキュメントの更新

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

You can pass an instance of UpdateOptions to the UpdateOne() method in order to customize its behavior.

次の例では、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」ガイドを参照してください。

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