개요
이 섹션에서는 쓰기 작업을 호출하여 MongoDB database의 collection에서 문서를 remove 하는 방법을 보여줍니다.
삭제
컬렉션에서 기존 문서를 제거하려면 deleteOne() 을 사용하여 문서 하나를 제거하거나 deleteMany() 을 사용하여 하나 이상의 문서를 제거할 수 있습니다. 이 메서드는 삭제하려는 문서와 일치하는 쿼리 문서를 허용합니다.
참고
애플리케이션 삭제 후 삭제된 문서에 대한 정보를 사용하는 경우 컬렉션.findOneAndDelete() 메서드는 deleteOne() 와 인터페이스가 비슷하지만 삭제된 문서 도 반환합니다.
다음과 같이 JSON 객체에서 deleteOne() 또는 deleteMany() 쓰기 작업으로 삭제할 문서를 지정할 수 있습니다.
const doc = { pageViews: { $gt: 10, $lt: 32768 }};deleteOne() 메서드를 사용하여 첫 번째로 일치하는 문서를 삭제하거나 deleteMany() 메서드를 사용하여 일치하는 모든 문서를 삭제하려면 문서를 메서드 매개 변수로 전달합니다.
const deleteResult = await myColl.deleteOne(doc);const deleteManyResult = await myColl.deleteMany(doc);위의 각 메서드 호출에 대한 결과의 deletedCount 필드에 다음과 같이 액세스하여 작업으로 삭제된 문서 수를 출력할 수 있습니다.
console.dir(deleteResult.deletedCount);console.dir(deleteManyResult.deletedCount);삭제 작업이 성공하면 이러한 명령문은 관련 작업으로 삭제된 문서 수를 출력합니다.
deleteOne() 예제: 전체 파일
참고
설정 예시
이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스 연결에 대해 자세히 알아보려면 MongoDB 연결 가이드를 참조하세요. 이 예시에서는 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기에 따라 MongoDB Atlas의 무료 클러스터에 있는 데이터베이스에 로드할 수 있습니다.
참고
타입스크립트 (Typescript) 관련 기능 없음
다음 코드 예시 JavaScript 사용합니다. 이 사용 사례 와 관련된 운전자 의 타입스크립트 (Typescript) 특정 기능은 없습니다.
다음 코드는 하나 삭제 작업을 수행하는 완전한 독립형 파일 입니다.
// Delete a document
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies");
/* Delete the first document in the "movies" collection that matches the specified query document */ const query = { title: "Annie Hall" }; const result = await movies.deleteOne(query);
/* Print a message that indicates whether the operation deleted a document */ if (result.deletedCount === 1) { console.log("Successfully deleted one document."); } else { console.log("No documents matched the query. Deleted 0 documents."); } } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown exceptionsrun().catch(console.dir);앞의 예시를 실행하면 다음과 같은 결과가 출력됩니다.
Successfully deleted one document.예시 두 번 이상 실행 첫 번째 실행 에서 일치하는 문서 삭제했기 때문에 다음과 같은 출력이 생성됩니다.
No documents matched the query. Deleted 0 documents.deleteMany() 예제: 전체 파일
참고
설정 예시
이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스 연결에 대해 자세히 알아보려면 MongoDB 연결 가이드를 참조하세요. 이 예시에서는 Atlas 샘플 데이터 세트에 포함된 sample_mflix 데이터베이스의 movies 컬렉션도 사용합니다. MongoDB 시작하기에 따라 MongoDB Atlas의 무료 클러스터에 있는 데이터베이스에 로드할 수 있습니다.
다음 코드는 다수 삭제 작업을 수행하는 완전한 독립형 파일 입니다.
// Delete multiple documents
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies");
/* Delete all documents that match the specified regular expression in the title field from the "movies" collection */ const query = { title: { $regex: "Santa" } }; const result = await movies.deleteMany(query);
// Print the number of deleted documents console.log("Deleted " + result.deletedCount + " documents"); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown exceptionsrun().catch(console.dir);// Delete multiple documents
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies");
/* Delete all documents that match the specified regular expression in the title field from the "movies" collection */ const result = await movies.deleteMany({ title: { $regex: "Santa" } }); // Print the number of deleted documents console.log("Deleted " + result.deletedCount + " documents"); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown exceptionsrun().catch(console.dir);앞의 예시 처음 실행하면 다음과 같은 결과가 출력됩니다.
Deleted 19 documents예제를 두 번 이상 실행하는 경우 첫 번째 실행에서 일치하는 문서를 삭제했기 때문에 다음과 같은 출력이 표시됩니다.
Deleted 0 documentsAPI 문서
이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.