Docs Menu

ドキュメントの置換

In this guide, you can learn how to replace documents in a MongoDB collection. A replace operation specifies the fields and values to replace a single document from your collection.

置換操作により、コレクションの 1 つのドキュメントが置き換えられます。 置換は、クエリフィルターが一致するドキュメントと置換ドキュメントの間で発生します。

replaceOne() メソッドは、一致するドキュメント内のすべての既存のフィールドと値(_id フィールドを除く)を削除し、それを置換ドキュメントに置き換えます。

次のように、 MongoCollectionインスタンスでreplaceOne()メソッドを呼び出すことができます。

collection.replaceOne(<query>, <replacement>);

replaceOne() メソッドには次のパラメーターがあります。

  • query は、コレクション内で置換するドキュメントと一致する条件を指定するクエリフィルターを指定します。

  • replacement は、一致したドキュメントを置き換える新しい Documentオブジェクトのフィールドと値を指定します。

  • (任意)replaceOptions は、ドライバーが置換操作を実行する方法をカスタマイズするために設定できるオプションを指定します。このタイプの詳細については、「ReplaceOptions の API ドキュメント」を参照してください。

In this example, a paint store sells five different colors of paint. The paint_inventory collection represents their current inventory:

{ "_id": 1, "color": "red", "qty": 5 }
{ "_id": 2, "color": "purple", "qty": 8 }
{ "_id": 3, "color": "yellow", "qty": 0 }
{ "_id": 4, "color": "green", "qty": 6 }
{ "_id": 5, "color": "pink", "qty": 0 }

塗料店では、在庫を再度更新する必要があることが認識されています。 25 20

在庫をアップデートするには、以下を指定してreplaceOne()メソッドを呼び出します。

  • colorが「pink」であるドキュメントに一致するクエリフィルター

  • colorが "Orange" で、 qtyが " 25である置換ドキュメント

Bson filter = Filters.eq("color", "pink");
Document document = new Document("color", "orange").append("qty", 25);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(filter, document);
// Prints the number of matched and modified documents
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

上記のコードの出力は、次のようになります。

Matched document count: 1
Modified document count: 1

以下は更新されたドキュメントを示しています。

{ "_id": 5, "color": "orange", "qty": 25 }

複数のドキュメントが replaceOne() メソッドで指定されたクエリフィルターに一致する場合は、最初の結果が置き換えられます。次のコードに示すように、サーバーが置換操作を実行する前に、一致したドキュメントに順序を適用するために、ReplaceOptionsインスタンスで並べ替えを指定できます。

ReplaceOptions options = ReplaceOptions.sort(ascending("qty"));
UpdateResult result = collection.replaceOne(filter, document, options);

置換操作でクエリフィルターに一致するドキュメントがない場合、 replaceOne()はコレクション内のドキュメントに変更を加えません。 一致するドキュメントがない場合に、ドキュメントを置き換える代わりに新しいドキュメントを挿入する方法については、アップサート ガイドを参照してください。

重要

replaceOne()メソッドは、コレクションの一意のインデックス制約に違反するドキュメントを変更することはできません。 一意なインデックスの制約の詳細については、 マニュアルの「 一意 なインデックスMongoDB Server 」を参照してください。