개요
업데이트 및 대체 작업을 사용하여 MongoDB 컬렉션의 문서를 수정할 수 있습니다. 업데이트 작업은 그 밖의 필드와 값을 변경하지 않고 유지하면서 문서의 필드와 값을 수정합니다. 대체 작업은 _id
필드 값을 변경하지 않고 기존 문서의 모든 필드와 값을 지정된 필드 및 값으로 대체합니다.
Node.js 드라이버는 다음과 같은 방법을 제공하여 문서를 변경하합니다.
updateOne()
updateMany()
replaceOne()
문서를 교체하는 방법을 학습 문서 교체 가이드 참조하세요.
팁
인터랙티브 랩
이 페이지에는 updateMany()
메서드를 사용하여 데이터를 수정하는 방법을 보여주는 짧은 인터랙티브 실습이 포함되어 있습니다. MongoDB 또는 코드 편집기를 설치하지 않고도 브라우저 창에서 직접 이 실습을 완료할 수 있습니다.
실습을 시작하려면 페이지 상단의 Open Interactive Tutorial 버튼을 클릭하세요. 실습을 전체 화면 형식으로 확장하려면 실습 창의 오른쪽 상단 모서리에 있는 전체 화면 버튼(⛶)을 클릭합니다.
문서 업데이트
하나 이상의 문서를 업데이트하려면 업데이트 연산자 (수행할 업데이트 유형)와 변경 내용을 설명하는 필드 및 값을 지정하는 업데이트 문서를 만듭니다. 업데이트 문서는 다음과 같은 포맷을 사용합니다.
{ <update operator>: { <field> : { ... }, <field> : { } }, <update operator>: { ... } }
업데이트 문서의 최상위 수준에는 다음과 같은 업데이트 연산자 중 하나 이상이 있습니다.
$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 // 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 문서를 참조하세요.