You can replace a single document using the collection.replaceOne() method. replaceOne()
accepts a query document and a replacement document. If the query matches a document in the collection, it replaces the first document that matches the query with the provided replacement document. This operation removes all fields and values in the original document and replaces them with the fields and values in the replacement document. The value of the _id
field remains the same unless you explicitly specify a new value for _id
in the replacement document.
任意のoptions
パラメータを使用して、 upsert
などの他のオプションを指定できます。 upsert
オプション フィールドをtrue
に設定すると、クエリに一致するドキュメントがない場合、このメソッドは新しいドキュメントを挿入します。
replaceOne()
メソッドは、実行中にエラーが発生した場合に例外をスローします。 たとえば、一意なインデックスのルールに違反する値を指定すると、 replaceOne()
はduplicate key error
をスローします。
注意
If your application requires the document after updating, use the collection.findOneAndReplace() method which has a similar interface to replaceOne()
. You can configure findOneAndReplace()
to return either the original matched document or the replacement document.
例
注意
この例を使用して、MongoDB のインスタンスに接続し、サンプルデータを含むデータベースと交流できます。MongoDB インスタンスへの接続とサンプルデータセットの読み込みの詳細については、 使用例ガイドを参照してください。
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a query for documents where the title contains "The Cat from" 16 const query = { title: { $regex: "The Cat from" } }; 17 18 // Create the document that will replace the existing document 19 const replacement = { 20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, 21 }; 22 23 // Execute the replace operation 24 const result = await movies.replaceOne(query, replacement); 25 26 // Print the result 27 console.log(`Modified ${result.modifiedCount} document(s)`); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 title: string; 10 } 11 12 async function run() { 13 try { 14 const database = client.db("sample_mflix"); 15 const movies = database.collection<Movie>("movies"); 16 17 const result = await movies.replaceOne( 18 { title: { $regex: "The Cat from" } }, 19 { 20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`, 21 } 22 ); 23 console.log(`Modified ${result.modifiedCount} document(s)`); 24 } finally { 25 await client.close(); 26 } 27 } 28 run().catch(console.dir);
前の例を実行すると、次の出力が表示されます。
Modified 1 document(s)