문서 메뉴
문서 홈
/ / /
Node.js 드라이버
/ /

여러 문서 삭제

collection.deleteMany() 메서드를 사용하여 컬렉션의 여러 문서를 한 번에 삭제할 수 있습니다. 쿼리 문서를 deleteMany() 메서드에 전달해 컬렉션에서 삭제할 문서의 하위 집합을 지정합니다. 쿼리 문서를 제공하지 않는 경우(또는 빈 문서를 제공하는 경우) MongoDB는 컬렉션의 모든 문서를 일치시켜 삭제합니다. deleteMany()를 사용하여 컬렉션의 모든 문서를 삭제할 수 있지만 성능 향상과 코드 명확성을 위해 drop()을 사용하는 것이 좋습니다.

deleteMany() 메서드의 두 번째 매개 변수에 전달된 options 개체에 더 많은 옵션을 지정할 수 있습니다. 자세한 내용은 deleteMany() API 설명서를 참조하세요.

다음 스니펫은 movies 컬렉션에서 여러 문서를 삭제합니다. 이는 쿼리 문서를 사용해 제목이 '산타클로스'인 동영상을 일치시키고 삭제하도록 쿼리를 구성합니다.

참고

이 예제를 사용하여 MongoDB 인스턴스에 연결하고 샘플 데이터가 포함된 데이터베이스와 상호 작용할 수 있습니다. MongoDB 인스턴스에 연결하고 샘플 데이터 세트를 로드하는 방법에 대해 자세히 알아보려면 사용 예제 가이드를 참조하세요.

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

돌아가기

문서 삭제

다음

문서 수 계산