Docs Menu
Docs Home
/ / /
Node.js 드라이버
/

문서 삭제

이 섹션에서는 쓰기 작업을 호출하여 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);

삭제 작업이 성공하면 이러한 명령문은 관련 작업으로 삭제된 문서 수를 출력합니다.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoDB 에 연결 가이드 참조하세요. 이 예시 movies sample_mflix Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

참고

TypeScript 관련 기능 없음

다음 코드 예시 JavaScript 사용합니다. 이 사용 사례 와 관련된 운전자 의 TypeScript 특정 기능은 없습니다.

다음 코드는 하나의 삭제 작업을 수행하는 완전한 독립형 파일 입니다.

1// Delete a document
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Delete the first document in the "movies" collection that matches
16 the specified query document */
17 const query = { title: "Annie Hall" };
18 const result = await movies.deleteOne(query);
19
20 /* Print a message that indicates whether the operation deleted a
21 document */
22 if (result.deletedCount === 1) {
23 console.log("Successfully deleted one document.");
24 } else {
25 console.log("No documents matched the query. Deleted 0 documents.");
26 }
27 } finally {
28 // Close the connection after the operation completes
29 await client.close();
30 }
31}
32// Run the program and print any thrown exceptions
33run().catch(console.dir);

앞의 예시를 실행하면 다음과 같은 결과가 출력됩니다.

Successfully deleted one document.

예시 두 번 이상 실행 첫 번째 실행 에서 일치하는 문서 삭제했기 때문에 다음과 같은 출력이 생성됩니다.

No documents matched the query. Deleted 0 documents.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoDB 에 연결 가이드 참조하세요. 이 예시 movies sample_mflix Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 코드는 다수 삭제 작업을 수행하는 완전한 독립형 파일 입니다.

1// Delete multiple documents
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string.
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Delete all documents that match the specified regular
16 expression in the title field from the "movies" collection */
17 const query = { title: { $regex: "Santa" } };
18 const result = await movies.deleteMany(query);
19
20 // Print the number of deleted documents
21 console.log("Deleted " + result.deletedCount + " documents");
22 } finally {
23 // Close the connection after the operation completes
24 await client.close();
25 }
26}
27// Run the program and print any thrown exceptions
28run().catch(console.dir);
1// Delete multiple documents
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Delete all documents that match the specified regular
16 expression in the title field from the "movies" collection */
17 const result = await movies.deleteMany({ title: { $regex: "Santa" } });
18
19 // Print the number of deleted documents
20 console.log("Deleted " + result.deletedCount + " documents");
21 } finally {
22 // Close the connection after the operation completes
23 await client.close();
24 }
25}
26// Run the program and print any thrown exceptions
27run().catch(console.dir);

앞의 예시 처음 실행하면 다음과 같은 결과가 출력됩니다.

Deleted 19 documents

예제를 두 번 이상 실행하는 경우 첫 번째 실행에서 일치하는 문서를 삭제했기 때문에 다음과 같은 출력이 표시됩니다.

Deleted 0 documents

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

배열 업데이트

이 페이지의 내용