개요
이 가이드 에서는 Node.js 운전자 사용하여 MongoDB 컬렉션 의 문서 에서 바꾸기 작업을 수행하는 방법을 학습 수 있습니다. 바꾸기 작업은 업데이트 작업과 다르게 수행됩니다. 업데이트 작업은 대상 문서 에서 지정된 필드만 수정합니다. 바꾸기 작업은 대상 문서의 모든 필드를 제거하고 새 필드로 바꿉니다.
문서 교체하기
대체 작업을 수행하려면 대체 작업에 사용할 필드와 값으로 구성된 대체 문서 를 만듭니다. 대체 문서는 다음 형식을 사용합니다.
{ <field>: { <value> }, <field>: { ... } }
대체 문서란 쿼리 필터와 일치하는 기존 문서를 대체하려는 문서를 말합니다.
선택적 options
매개변수를 사용하여 upsert
과 같은 더 많은 옵션을 지정할 수 있습니다. upsert
옵션 필드 true
로 설정하다 메서드는 쿼리 와 일치하는 문서 없을 때 새 문서 삽입합니다.
실행 중에 오류가 발생하면 replaceOne()
메서드에서 예외가 발생합니다. 예를 들어, 고유 인덱스 규칙을 위반하는 값을 지정하면 replaceOne()
duplicate key error
이(가) 발생합니다.
참고
예시
판매할 항목, 가격, 사용 가능한 수량을 설명하는 필드가 있는 myDB.items
컬렉션의 문서를 감안합니다.
{ _id: 501, item: "3-wick beeswax candle", price: 18.99, quantity: 10, }
이 문서를 완전히 다른 항목에 대한 설명이 포함된 문서로 대체하려고 한다고 가정해 보겠습니다. 대체 작업은 다음과 같이 유사할 수 있습니다.
const myDB = client.db("myDB"); const myColl = myDB.collection("items"); const filter = { _id: 501 }; // replace the matched document with the replacement document const replacementDocument = { item: "Vintage silver flatware set", price: 79.15, quantity: 1, }; const result = await myColl.replaceOne(filter, replacementDocument);
대체된 문서에는 다음과 같이 대체 문서의 내용과 변경할 수 없는 _id
필드 등이 있습니다.
{ _id: 501, item: "Vintage silver flatware set", price: 79.15, quantity: 1, }
대체 작업이 컬렉션 의 문서와 일치하지 않는 경우 변경되지 않습니다. 대체를 시도하는 업서트 수행하도록 대체 작업을 구성할 수 있지만 일치하는 문서가 없는 경우 지정된 필드와 값이 포함된 새 문서 삽입합니다.
문서의 _id
필드를 수정하거나 고유 인덱스 제약 조건을 위반하는 값으로 필드를 변경할 수 없습니다. 고유 인덱스에 대한 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.
replaceOne() 예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoDB 에 연결 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_mflix
데이터베이스의 movies
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
다음 코드는 하나의 교체 작업을 수행하는 완전한 독립형 파일 입니다.
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)
API 문서
이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.