Docs Menu

삭제

delete

The delete command removes documents from a collection. A single delete command can contain multiple delete specifications. The delete methods provided by the MongoDB drivers use this command internally.

버전 5.0에서 변경됨

In mongosh, this command can also be run through the deleteOne(), deleteMany(), and findOneAndDelete() helper methods.

헬퍼 메서드는 mongosh 사용자에게 편리하지만 데이터베이스 명령과 동일한 수준의 정보를 반환하지 못할 수 있습니다. 편의가 필요하지 않거나 추가 리턴 필드가 필요한 경우 데이터베이스 명령을 사용합니다.

반환합니다:작업 상태가 포함된 문서입니다. 자세한 내용은 출력을 참조하세요.

이 명령은 다음 환경에서 호스팅되는 배포에서 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

참고

이 명령은 모든 MongoDB Atlas 클러스터에서 지원됩니다. 모든 명령에 대한 Atlas 지원에 관해 자세히 알아보려면 지원되지 않는 명령을 참조하십시오.

명령은 다음과 같은 구문을 가집니다:

db.runCommand(
{
delete: <collection>,
deletes: [
{
q : <query>,
limit : <integer>,
collation: <document>,
hint: <document|string>
},
...
],
comment: <any>,
let: <document>, // Added in MongoDB 5.0
ordered: <boolean>,
writeConcern: { <write concern> },
maxTimeMS: <integer>
}
)

이 명령은 다음 필드를 사용합니다.

필드
유형
설명

문자열

대상 컬렉션의 이름입니다.

배열

An array of one or more delete statements to perform in the named collection.

comment

any

선택 사항. 이 명령에 첨부할 사용자 제공 코멘트입니다. 설정되면 이 설명은 다음 위치에서 이 명령의 레코드와 함께 표시됩니다.

댓글은 유효한 모든 BSON types (문자열, 정수, 객체, 배열 등)이 될 수 있습니다.

문서

선택 사항.

변수 목록이 있는 문서를 지정합니다. 이를 통해 쿼리 텍스트에서 변수를 분리하여 명령 가독성을 향상시킬 수 있습니다.

문서 구문은 다음과 같습니다:

{
<variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n>
}

변수는 표현식에서 반환된 값으로 설정되며 이후에는 변경할 수 없습니다.

명령에서 변수 값에 액세스하려면 $<variable_name> 형식의 이중 달러 기호 접두사 ($) 를 변수 이름과 함께 사용하십시오.예시: $targetTotal.

변수를 사용하여 결과를 필터링하려면 $expr 연산자 내에서 변수에 액세스해야 합니다.

For a complete example using let and variables, see Use Variables in let.

버전 5.0에 추가.

부울

Optional. If true, then when a delete statement fails, return without performing the remaining delete statements. If false, then when a delete statement fails, continue with the remaining delete statements, if any. Defaults to true.

문서

선택 사항. 명령의 쓰기 고려 delete (write concern) 를 Express하는 문서입니다. 기본 쓰기 고려 (write concern)를 사용하려면 생략합니다.

트랜잭션에서 실행되는 경우 작업에 대한 쓰기 고려를 명시적으로 설정하지 마세요. 트랜잭션에 쓰기 고려를 사용하려면 트랜잭션 및 쓰기 고려를 참조하세요.

maxTimeMS

non-negative integer

선택 사항.

시간 제한을 밀리초 단위로 지정합니다. maxTimeMS에 값을 지정하지 않으면 작업이 시간 초과되지 않습니다. 0 값은 바인딩되지 않는 기본 동작을 명시적으로 지정합니다.

MongoDB는 db.killOp()와 동일한 메커니즘을 사용하여 할당된 시간 제한을 초과하는 작업을 종료합니다. MongoDB는 지정된 중단 지점 중 하나에서만 작업을 종료합니다.

Each element of the deletes array contains the following fields:

필드
유형
설명

문서

The query that matches documents to delete.

integer

The number of matching documents to delete. Specify either a 0 to delete all matching documents or 1 to delete a single document.

문서

선택 사항.

작업에 사용할 데이터 정렬을 지정합니다.

데이터 정렬을 사용하면 대소문자 및 악센트 표시 규칙과 같은 문자열 비교에 대한 언어별 규칙을 지정할 수 있습니다.

데이터 정렬 옵션의 구문은 다음과 같습니다:

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

데이터 정렬을 지정할 때 locale 필드는 필수이고, 다른 데이터 정렬 필드는 모두 선택 사항입니다. 필드에 대한 설명은 데이터 정렬 문서를 참조하세요.

데이터 정렬이 지정되지 않았지만 컬렉션에 기본 데이터 정렬이 있는 경우( db.createCollection() 참조), 작업은 컬렉션에 지정된 데이터 정렬을 사용합니다.

컬렉션 또는 연산에 대한 데이터 정렬이 지정되지 않은 경우, MongoDB는 이전 버전에서 문자열 비교에 사용된 간단한 이진 비교를 사용합니다.

한 연산에 대해 여러 데이터 정렬을 지정할 수 없습니다. 예를 들어 필드별로 서로 다른 데이터 정렬을 지정할 수 없으며 정렬과 함께 찾기를 수행하는 경우 찾기 와 정렬에서 각각 다른 데이터 정렬을 사용하는 것은 허용되지 않습니다.

문서 또는 문자열

선택 사항. 쿼리 조건자를 지원 데 사용할 인덱스지정하는 문서 또는 문자열입니다.

이 옵션은 인덱스 사양 문서 또는 인덱스 이름 문자열을 사용할 수 있습니다.

존재하지 않는 인덱스를 지정하면 연산 오류가 발생합니다.

예시 hint 는 삭제 작업에 지정을 참조하세요.

To use delete operations for a sharded collection that specify the limit: 1 option:

  • 하나의 샤드만 대상으로 하는 경우 쿼리 사양에서 부분 샤드 키를 사용할 수 있습니다.

  • 쿼리 사양에서 샤드 키 또는 _id 필드를 제공할 수 있습니다.

The total size of all the queries (i.e. the q field values) in the deletes array must be less than or equal to the maximum BSON document size.

The total number of delete documents in the deletes array must be less than or equal to the maximum bulk size.

삭제 can be used inside distributed transactions.

트랜잭션에서 실행되는 경우 작업에 대한 쓰기 고려를 명시적으로 설정하지 마세요. 트랜잭션에 쓰기 고려를 사용하려면 트랜잭션 및 쓰기 고려를 참조하세요.

중요

대부분의 경우 분산 트랜잭션은 단일 문서 쓰기에 비해 더 큰 성능 비용이 발생하므로 분산 트랜잭션의 가용성이 효과적인 스키마 설계를 대체할 수는 없습니다. 대부분의 시나리오에서 비정규화된 데이터 모델 (내장된 문서 및 배열) 은 계속해서 데이터 및 사용 사례에 최적일 것입니다. 즉, 대부분의 시나리오에서 데이터를 적절하게 모델링하면 분산 트랜잭션의 필요성이 최소화됩니다.

추가 트랜잭션 사용 고려 사항(예: 런타임 제한 및 oplog 크기 제한)은 프로덕션 고려사항을 참조하세요.

The following example deletes from the orders collection one document that has the status equal to D by specifying the limit of 1:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 1 } ]
}
)

The returned document shows that the command deleted 1 document. See 출력 for details.

{ "ok" : 1, "n" : 1 }

참고

To use delete operations for a sharded collection that specify the limit: 1 option:

  • 하나의 샤드만 대상으로 하는 경우 쿼리 사양에서 부분 샤드 키를 사용할 수 있습니다.

  • 쿼리 사양에서 샤드 키 또는 _id 필드를 제공할 수 있습니다.

The following example deletes from the orders collection all documents that have the status equal to D by specifying the limit of 0:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

The returned document shows that the command found and deleted 13 documents. See 출력 for details.

{ "ok" : 1, "n" : 13 }

참고

If you are deleting all documents in a large collection, it may be faster to drop the collection and recreate it. Before dropping the collection, note all indexes on the collection. You must recreate any indexes that existed in the original collection. If the original collection was sharded, you must also 샤드 the recreated collection.

For more information on dropping a collection, see db.collection.drop().

Delete all documents in the orders collection by specifying an empty query condition and a limit of 0:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

The returned document shows that the command found and deleted 35 documents in total. See 출력 for details.

{ "ok" : 1, "n" : 35 }

The following example performs multiple delete operations on the orders collection:

db.runCommand(
{
delete: "orders",
deletes: [
{ q: { status: "D" }, limit: 0 },
{ q: { cust_num: 99999, item: "abc123", status: "A" }, limit: 1 }
],
ordered: false,
writeConcern: { w: 1 }
}
)

The returned document shows that the command found and deleted 21 documents in total for the two delete statements. See 출력 for details.

{ "ok" : 1, "n" : 21 }

데이터 정렬을 사용하면 대소문자 및 악센트 표시 규칙과 같은 문자열 비교에 대한 언어별 규칙을 지정할 수 있습니다.

컬렉션 myColl에는 다음 문서가 있습니다.

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

다음 작업에는 데이터 정렬 옵션이 포함됩니다.

db.runCommand({
delete: "myColl",
deletes: [
{ q: { category: "cafe", status: "a" }, limit: 0, collation: { locale: "fr", strength: 1 } }
]
})

mongosh에서 다음 문서를 사용하여 members 컬렉션을 생성하세요.

db.members.insertMany([
{ "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
{ "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
{ "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
])

컬렉션에 다음 인덱스를 만듭니다.

db.members.createIndex( { status: 1 } )
db.members.createIndex( { points: 1 } )

다음 업데이트 작업은 인덱스 { status: 1 }을(를) 사용하도록 명시적으로 암시합니다.

db.runCommand({
delete: "members",
deletes: [
{ q: { "points": { $lte: 20 }, "status": "P" }, limit: 0, hint: { status: 1 } }
]
})

참고

존재하지 않는 인덱스를 지정하면 연산 오류가 발생합니다.

사용된 인덱스를 보려면 작업에 대해 explain을 실행하세요.

db.runCommand(
{
explain: {
delete: "members",
deletes: [
{ q: { "points": { $lte: 20 }, "status": "P" }, limit: 0, hint: { status: 1 } }
]
},
verbosity: "queryPlanner"
}
)

버전 5.0에 추가.

명령의 다른 곳에서 액세스할 수 있는 변수를 정의하려면 let 옵션을 사용합니다.

참고

변수를 사용하여 결과를 필터링하려면 $expr 연산자 내에서 변수에 액세스해야 합니다.

컬렉션 cakeFlavors을 만듭니다:

db.cakeFlavors.insertMany( [
{ _id: 1, flavor: "chocolate" },
{ _id: 2, flavor: "strawberry" },
{ _id: 3, flavor: "cherry" }
] )

The following example defines a targetFlavor variable in let and uses the variable to delete the strawberry cake flavor:

db.runCommand( {
delete: db.cakeFlavors.getName(),
deletes: [ {
q: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
limit: 1
} ],
let : { targetFlavor: "strawberry" }
} )

반환된 문서에는 다음 필드의 하위 집합이 포함되어 있습니다.

delete.ok

명령의 상태입니다.

delete.n

The number of documents deleted.

delete.writeErrors

An array of documents that contains information regarding any error encountered during the delete operation. The writeErrors array contains an error document for each delete statement that errors.

Each error document contains the following information:

delete.writeErrors.index

An integer that identifies the delete statement in the deletes array, which uses a zero-based index.

delete.writeErrors.code

오류를 식별하는 정수 값입니다.

delete.writeErrors.errmsg

오류에 대한 설명입니다.

delete.writeConcernError

쓰기 고려 (write concern) 와 관련된 오류를 설명하는 문서입니다.

버전 에서 7.0.6 변경됨: (및 에서도 사용 6.0.14 5.0.30 가능): delete 가 에서 실행되면 하나 이상의 쓰기 (write) 오류가 발생하더라도 쓰기 고려 (write concern) 오류가 항상 mongos 보고됩니다. 이전 릴리스에서는 쓰기 (write) 오류가 발생하면 이(가 ) 쓰기 delete 고려 (write concern) 오류를 보고하지 않을 수 있었습니다.

The writeConcernError documents contian the following fields:

delete.writeConcernError.code

쓰기 문제 오류의 원인을 식별하는 정수 값입니다.

delete.writeConcernError.errmsg

쓰기 관련 오류의 원인에 대한 설명입니다.

delete.writeConcernError.errInfo.writeConcern

해당 작업에 사용되는 쓰기 관련 객체입니다. 쓰기 문제 객체 필드에 대한 자세한 내용은 쓰기 문제 사양을 참조하세요.

쓰기 고려 객체에는 쓰기 문제의 원본을 나타내는 다음 필드도 포함될 수 있습니다.

delete.writeConcernError.errInfo.writeConcern.provenance

쓰기 문제가 발생한 위치를 나타내는 문자열 값입니다(쓰기 문제 provenance 라고도 함). 다음 표에는 이 필드에 사용할 수 있는 값과 그 의미가 나와 있습니다.

출처
설명

clientSupplied

쓰기 우려 사항은 애플리케이션에서 지정되었습니다.

customDefault

쓰기 고려는 사용자 정의된 기본값에서 비롯된 것입니다. setDefaultRWConcern을 참조하십시오.

getLastErrorDefaults

쓰기 고려는 복제본 세트의 settings.getLastErrorDefaults 필드에서 발생했습니다.

implicitDefault

쓰기 고려는 다른 모든 쓰기 고려 사양이 없는 상태에서 서버에서 발생했습니다.

The following is an example document returned for a successful delete command:

{ ok: 1, n: 1 }

The following is an example document returned for a delete command that encountered an error because it specified a non-existent index in the hint field:

{
n: 0,
writeErrors: [
{
index: 0,
code: 2,
errmsg: 'error processing query: ns=test.products: hat $eq "bowler"\n' +
'Sort: {}\n' +
'Proj: {}\n' +
' planner returned error :: caused by :: hint provided does not correspond to an existing index'
}
],
ok: 1
}