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
이(가) 발생합니다.
참고
예시
참고
이 예시를 사용하여 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)