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

ドキュメントの変更

MongoDB コレクション内のドキュメントを変更するには、更新操作と置換操作を使用します。 更新操作は、ドキュメントのフィールドと値を変更しながら、他のフィールドと値を変更せずに維持します。 置換操作は、 _idフィールド値を変更せずに、既存のドキュメント内のすべてのフィールドと値を指定されたフィールドと値で置き換えます。

Node.js ドライバーは、ドキュメントを変更するための次のメソッドを提供します。

  • updateOne()

  • updateMany()

  • replaceOne()

ドキュメントを置き換える方法については、 「ドキュメントの置き換え」ガイドを参照してください。

Tip

インタラクティブ ラボ

このページには、 updateMany()メソッドを使用してデータを変更する方法を示す短いインタラクティブ ラボが含まれています。 MongoDB やコード エディターをインストールしなくても、ブラウザ ウィンドウでこのラボを直接完了できます。

ラボを開始するには、ページ上部の [ Open Interactive Tutorial ] ボタンをクリックします。 ラボを全画面形式に展開するには、ラボ ペインの右上隅にある全画面ボタン( ⛶ )をクリックします。

1 つ以上のドキュメントに対して更新を実行するには、更新演算子(実行する更新のタイプ)と変更を説明するフィールドと値を指定する更新ドキュメントを作成します。 更新ドキュメントは、次の形式を使用します。

{ <update operator>: { <field> : { ... }, <field> : { } }, <update operator>: { ... }}

更新ドキュメントの最上位には、次の更新演算子が 1 つ以上含まれています。

  • $set: フィールドの値を指定された値に置き換えます

  • $inc: フィールド値を増減します

  • $rename: フィールドの名前を変更します

  • $unset: フィールドを削除します

  • $mul: フィールド値に指定した数値を乗算します

更新演算子とその使用方法の完全なリストについては、MongoDB Server のマニュアルを参照してください。

更新演算子は、更新ドキュメント内の関連するフィールドにのみ適用されます。

注意

更新操作における集計パイプライン

MongoDB バージョン4.2以降を使用している場合は、更新操作で 集計ステージ のサブセットで構成された集計パイプラインを使用できます。 更新操作で使用される集計パイプラインで MongoDB がサポートする集計ステージの詳細については、 集計パイプラインを使用して更新を構築するに関するチュートリアル を参照してください。

販売商品、その価格、利用可能な数量を説明するフィールドを持つmyDB.itemsコレクション内のドキュメントを例にとります。

{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 7,}

quantityに新しい値を使用して$set更新演算子を適用すると、次の更新ドキュメントを使用できます。

const myDB = client.db("myDB");const myColl = myDB.collection("items"); const filter = { _id: 465 }; // update the value of the 'quantity' field to 5const updateDocument = { $set: { quantity: 5, },};const result = await myColl.updateOne(filter, updateDocument);

更新されたドキュメントは次のようになりますquantityフィールドの値が更新され、他のすべての値は変更されていません。

{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 5,}

アップデート操作がコレクション内のいずれかのドキュメントと一致しない場合、変更は行われません。 更新操作は、更新を実行しようとするアップサートを実行するように構成できますが、一致するドキュメントがない場合は、指定されたフィールドと値を持つ新しいドキュメントを挿入します。

ドキュメントの_idフィールドを変更したり、 一意のインデックス制約に違反する値にフィールドを変更したりすることはできません。 一意なインデックス の詳細については、MongoDB Server マニュアルを参照してください。

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoDB への接続」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB Get Startedに従って、MongoDB Atlasの無料クラスター上のデータベースに読み込むことができます。

この例では、ドキュメントフィールドの更新値を指定する $set 更新演算子を使用しています。更新演算子の詳細については、MongoDB更新演算子の参照ドキュメントを参照してください。

次のコードは、アップデートの 1 つの操作を実行する完全なスタンドアロンファイルです。

// Update a document import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a filter for movies with the title "Random Harvest" const filter = { title: "Random Harvest" }; /* Set the upsert option to insert a document if no documents match the filter */ const options = { upsert: true }; // Specify the update to set a value for the plot field const updateDoc = { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}` }, }; // Update the first document that matches the filter const result = await movies.updateOne(filter, updateDoc, options); // Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, ); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown errorsrun().catch(console.dir);

上記の例を実行すると、次の出力が生成されます。

1 document(s) matched the filter, updated 1 document(s)

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoDB への接続」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB Get Startedに従って、MongoDB Atlasの無料クラスター上のデータベースに読み込むことができます。

次のコードは、アップデートの多くの操作を実行する完全なスタンドアロンファイルです。

/* Update multiple documents */ import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a filter to update all movies with a 'G' rating const filter = { rated: "G" }; // Create an update document specifying the change to make const updateDoc = { $set: { random_review: `After viewing I am ${ 100 * Math.random() }% more satisfied with life.`, }, }; // Update the documents that match the specified filter const result = await movies.updateMany(filter, updateDoc); console.log(`Updated ${result.modifiedCount} documents`); } finally { // Close the database connection on completion or error await client.close(); }}run().catch(console.dir);

前の例を実行すると、次のような出力が表示されます。

Updated 477 documents

このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。