Docs Menu
Docs Home
/ / /
Java Sync Driver
/

Update Documents

このガイドでは、 MongoDBコレクション内のドキュメントを更新する方法を学習できます。更新操作は、1 つ以上のドキュメント内の変更するフィールドと値を指定します。クエリフィルターに一致する 1 つ以上のドキュメントに、アップデートドキュメントで指定された変更を適用します。

埋め込み配列を更新する方法や 1 回の操作で更新または挿入する方法については、次のページを参照してください。

  • ドキュメント内の配列の更新

  • 1 回の操作で挿入またはアップデート

更新操作は、フィールドと値を変更します。

  • updateOne() メソッドは、クエリフィルターフィルターに一致する最初のドキュメントを変更し、

  • updateMany() メソッドは、クエリフィルターに一致するすべてのドキュメントを変更します。

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

collection.updateOne(<query>, <updateDocument>);
collection.updateMany(<query>, <updateDocument>);

updateOne()メソッドとupdateMany()メソッドにはどちらも次のパラメータがあります。

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

  • update は、一致するドキュメントつまたは複数のドキュメントで変更するフィールドと値を指定します。このセクションの例では、アップデート ビルダを使用してアップデートドキュメントを作成します。

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

次のように、 Updatesビルダを使用してupdateDocumentを作成できます。

Bson update = Updates.operator(<field>, <value>);

更新ビルダとその使用方法の完全なリストを表示するには、 APIドキュメントの「 更新 」を参照してください。

次の例では、塗料店で 5 色の塗料を販売しています。 paint_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 }

以下の例では、qty の値が 0 である最初に一致するドキュメントの color フィールドの値を変更する方法を示しています。

Bson filter = Filters.eq("qty", 0);
Bson update = Updates.set("color", "dandelion");
// Updates first matching document
UpdateResult result = collection.updateOne(filter, update);

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

UpdateOptions options = UpdateOptions.sort(ascending("color"));
UpdateResult result = collection.updateOne(filter, document, options);

塗料店で新しい商品を受け取ったので、在庫を更新する必要があります。 入荷には、各塗料塗料の20缶が含まれています。

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

  • すべての色に一致するクエリフィルター

  • qtyフィールドを20 ずつ増加させるための手順を含む更新ドキュメント

Bson filter = Filters.empty();
Bson update = Updates.inc("qty", 20);
// Updates all documents and prints the number of matched and modified documents
UpdateResult result = collection.updateMany(filter, update);
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

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

Matched document count: 5
Modified document count: 5

以下は、 paint_inventoryコレクション内の更新されたドキュメントを示しています。

{ "_id": 1, "color": "red", "qty": 25 }
{ "_id": 2, "color": "purple", "qty": 28 }
{ "_id": 3, "color": "yellow", "qty": 20 }
{ "_id": 4, "color": "green", "qty": 26 }
{ "_id": 5, "color": "pink", "qty": 20 }

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

重要

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

注意

セットアップ例

この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、MongoClient の作成 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflixデータベースの moviesコレクションも使用します。Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

次のコードは、1 つの更新操作と複数の更新操作を実行する完全なスタンドアロンファイルです。

// Updates the first document that matches a query filter by using the Java driver
package org.example;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.gt;
public class Update {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// Instructs the driver to insert a new document if none match the query
UpdateOptions options = new UpdateOptions().upsert(true);
Document updateOneQuery = new Document().append("title", "Cool Runnings 2");
// Creates instructions to update the values of three document fields
Bson updateOneUpdates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));
// Updates the first document that has a "title" value of "Cool Runnings 2"
UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options);
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
System.out.println("Number of documents updated - update one: " + result.getModifiedCount());
System.out.println("Upserted document ID: " + result.getUpsertedId());
Bson updateManyQuery = gt("num_mflix_comments", 50);
// Creates instructions to update the values of two document fields
Bson updateManyUpdates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));
// Updates documents that have a "num_mflix_comments" value over 50
UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates);
// Prints the number of updated documents
System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount());
}
}
}
updateOne() modified document count: 1
Upserted ID: null
updateMany() modified document count: 242

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

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

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

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

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

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

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

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

塗料店では、在庫を再度更新する必要があることが認識されています。 ページ内を表示

在庫をアップデートするには、以下を指定して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 」を参照してください。

注意

セットアップ例

この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、MongoClient の作成 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflixデータベースの moviesコレクションも使用します。Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

次のコードは、1 つの置き換え操作を実行する完全なスタンドアロンファイルです。

// Replaces the first document that matches a filter by using the Java driver
package org.example;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.ReplaceOptions;
import com.mongodb.client.result.UpdateResult;
public class ReplaceOne {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("title", "Music of the Heart");
// Creates a new document containing "title" and "fullplot" fields
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");
// Instructs the driver to insert a new document if none match the query
ReplaceOptions opts = new ReplaceOptions().upsert(true);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);
// Prints the number of modified documents and the upserted document ID, if an upsert was performed
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to replace due to an error: " + me);
}
}
}
Modified document count: 0
Upserted id: BsonObjectId{ ... }

このページで使用されているメソッドとクラスの詳細については、次のAPIドキュメントを参照してください。

戻る

カーソルからのデータへのアクセス

項目一覧