Overview
MongoDB コレクション内のドキュメントを変更するには、更新操作と置換操作を使用します。 更新操作は、ドキュメントのフィールドと値を変更しながら、他のフィールドと値を変更せずに維持します。 置換操作は、 _id
フィールド値を変更せずに、既存のドキュメント内のすべてのフィールドと値を指定されたフィールドと値で置き換えます。
Node.js ドライバーは、ドキュメントを変更するための次のメソッドを提供します。
updateOne()
updateMany()
replaceOne()
ドキュメントを置き換える方法については、ドキュメントの置き換えガイドを参照してください。
Tip
インタラクティブ ラボ
このページには、 updateMany()
メソッドを使用してデータを変更する方法を示す短いインタラクティブ ラボが含まれています。 MongoDB やコード エディターをインストールしなくても、ブラウザ ウィンドウでこのラボを直接完了できます。
ラボを開始するには、ページ上部の [ Open Interactive Tutorialボタンをクリックします。 ラボを全画面形式に展開するには、ラボ ペインの右上隅にある全画面ボタン( ⛶ )をクリックします。
Update Documents
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 5 const 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 マニュアルを参照してください。
updateOne() の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、 MongoDBへの接続 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflix
データベースの movies
コレクションも使用します。「Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
この例では、ドキュメントフィールドの更新値を指定する $set
更新演算子を使用しています。更新演算子の詳細については、MongoDB更新演算子の参照ドキュメントを参照してください。
次のコードは、アップデートの 1 つの操作を実行する完全なスタンドアロンファイルです。
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a filter for movies with the title "Random Harvest" 16 const filter = { title: "Random Harvest" }; 17 18 /* Set the upsert option to insert a document if no documents match 19 the filter */ 20 const options = { upsert: true }; 21 22 // Specify the update to set a value for the plot field 23 const updateDoc = { 24 $set: { 25 plot: `A harvest of random numbers, such as: ${Math.random()}` 26 }, 27 }; 28 29 // Update the first document that matches the filter 30 const result = await movies.updateOne(filter, updateDoc, options); 31 32 // Print the number of matching and modified documents 33 console.log( 34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, 35 ); 36 } finally { 37 // Close the connection after the operation completes 38 await client.close(); 39 } 40 } 41 // Run the program and print any thrown errors 42 run().catch(console.dir);
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 // Define the Movie interface 11 interface Movie { 12 plot: string; 13 title: string; 14 } 15 16 async function run() { 17 try { 18 const database = client.db("sample_mflix"); 19 const movies = database.collection<Movie>("movies"); 20 21 /* Update a document that has the title "Random Harvest" to have a 22 plot field with the specified value */ 23 const result = await movies.updateOne( 24 { title: "Random Harvest" }, 25 { 26 $set: { 27 plot: `A harvest of random numbers, such as: ${Math.random()}`, 28 }, 29 }, 30 /* Set the upsert option to insert a document if no documents 31 match the filter */ 32 { upsert: true } 33 ); 34 35 // Print the number of matching and modified documents 36 console.log( 37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)` 38 ); 39 } finally { 40 // Close the connection after the operation completes 41 await client.close(); 42 } 43 } 44 // Run the program and print any thrown errors 45 run().catch(console.dir);
上記の例を実行すると、次の出力が生成されます。
1 document(s) matched the filter, updated 1 document(s)
updateMany() の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、 MongoDBへの接続 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflix
データベースの movies
コレクションも使用します。「Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
次のコードは、アップデートの多くの操作を実行する完全なスタンドアロンファイルです。
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "movies" collection in the "sample_mflix" database 13 const database = client.db("sample_mflix"); 14 const movies = database.collection("movies"); 15 16 // Create a filter to update all movies with a 'G' rating 17 const filter = { rated: "G" }; 18 19 // Create an update document specifying the change to make 20 const updateDoc = { 21 $set: { 22 random_review: `After viewing I am ${ 23 100 * Math.random() 24 }% more satisfied with life.`, 25 }, 26 }; 27 // Update the documents that match the specified filter 28 const result = await movies.updateMany(filter, updateDoc); 29 console.log(`Updated ${result.modifiedCount} documents`); 30 } finally { 31 // Close the database connection on completion or error 32 await client.close(); 33 } 34 } 35 run().catch(console.dir);
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 enum Rating { 11 G = "G", 12 PG = "PG", 13 PG_13 = "PG-13", 14 R = "R", 15 NR = "NOT RATED", 16 } 17 18 // Create a Movie interface 19 interface Movie { 20 rated: Rating; 21 random_review?: string; 22 } 23 24 async function run() { 25 try { 26 // Get the "movies" collection in the "sample_mflix" database 27 const database = client.db("sample_mflix"); 28 const movies = database.collection<Movie>("movies"); 29 30 // Update all documents that match the specified filter 31 const result = await movies.updateMany( 32 { rated: Rating.G }, 33 { 34 $set: { 35 random_review: `After viewing I am ${ 36 100 * Math.random() 37 }% more satisfied with life.`, 38 }, 39 } 40 ); 41 console.log(`Updated ${result.modifiedCount} documents`); 42 } finally { 43 // Close the database connection on completion or error 44 await client.close(); 45 } 46 } 47 run().catch(console.dir);
前の例を実行すると、次のような出力が表示されます。
Updated 477 documents
API ドキュメント
このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。