정의
버전 8.0에 추가 되었습니다.
MongoDB 8.0 부터는 새로운 bulkWrite 명령을 사용하여 한 번의 요청 으로 여러 컬렉션에 대한 많은 삽입, 업데이트 및 삭제 작업을 수행할 수 있습니다. 기존 db.collection.bulkWrite() 메서드에서는 한 번의 요청 으로 하나의 컬렉션 만 수정할 수 있습니다.
bulkWrite 명령에서 각 컬렉션 을 지정하려면 네임스페이스 (데이터베이스 및 컬렉션 이름)를 사용합니다.
호환성
이 명령은 다음 환경에서 호스팅되는 배포에서 사용할 수 있습니다.
- MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스
참고
이 명령은 모든 MongoDB Atlas 클러스터에서 지원됩니다. 모든 명령에 대한 Atlas 지원에 관해 자세히 알아보려면 지원되지 않는 명령을 참조하십시오.
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
명령의 구문은 다음과 같습니다.
db.adminCommand( { bulkWrite: 1, // Include the insert, update, and delete operations // in the ops array ops: [ { insert: <integer>, // Namespace ID index for insert operation. // Must match a namespace ID index in // ns specified later in the nsInfo array. document: <document> }, { update: <integer>, // Namespace ID index for update operation filter: <document>, updateMods: <document>, arrayFilters: [ <filterDocument0>, <filterDocument1>, ... ], multi: <boolean>, hint: <document>, constants: <document>, collation: <document> }, { delete: <integer>, // Namespace ID index for delete operation filter: <document>, multi: <boolean>, hint: <document>, collation: <document> }, ... // Additional insert, update, and delete operations in any order ... ], // Include the namespaces with collections to modify // in the nsInfo array. You can add multiple namespaces here. nsInfo: [ { ns: <string>, // Namespace (database and collection name) to modify. // Each operation namespace ID index // specified in the earlier ops array must // match a namespace ID index here. collectionUUID: <string>, encryptionInformation: <document> }, ... // Additional namespaces ... ], // Additional fields ordered: <boolean>, bypassDocumentValidation: <boolean>, comment: <string>, let: <document>, errorsOnly: <boolean>, cursor: { batchSize: <integer> }, maxTimeMS: <integer>, writeConcern: <string> } )
명령 구문에서 여러 개를 지정할 수 있습니다.
ops배열 에서 임의의 순서로 삽입, 업데이트 및 삭제 작업을 수행할 수 있습니다.nsInfo배열 의 작업에 대한 네임스페이스입니다. 작업을 네임스페이스 와 일치시키려면 동일한 네임스페이스 ID 인덱스 를 사용합니다. 인덱스는0부터 시작합니다. 샤딩된 컬렉션을 사용할 수 있습니다.
명령 필드
이 명령은 다음 필드를 사용합니다.
필드 | 유형 | 필요성 | 설명 |
|---|---|---|---|
| integer | 필수 사항 | 삽입 작업의 네임스페이스 ID 인덱스 로, |
| 문서 | 필수 사항 | 컬렉션 에 삽입할 문서입니다. |
| integer | 필수 사항 | 업데이트 작업의 네임스페이스 ID 인덱스 로, |
| 문서 | 옵션 | 쿼리 선택기 를 사용하여 업데이트 또는 삭제 작업에 필요한 문서를 제한할 수 있습니다. |
| 문서 | 옵션 | |
| 문서 배열 | 옵션 | 배열 필드 에 대한 업데이트 작업을 위해 수정할 문서를 지정하는 필터하다 문서의 배열입니다. |
| 부울 | 옵션 |
기본값은 |
| 문서 | 옵션 | 문서 |
| 문서 | 옵션 | 집계 파이프라인 사용자 지정 업데이트 에 대한 상수입니다. |
| 문서 | 옵션 | 업데이트 또는 삭제 작업을 위한 데이터 정렬 입니다. |
| integer | 필수 사항 | 삭제 작업의 네임스페이스 ID 인덱스 로, |
| 문자열 | 필수 사항 | 작업을 위한 네임스페이스(데이터베이스 및 컬렉션)입니다. |
| 문자열 | 옵션 | 작업에 대한 컬렉션 을 지정하는 UUID 16진수 값입니다. |
| 문서 | 옵션 | 작업에 대한 암호화 정보 스키마 및 토큰입니다. 자세한 내용은 암호화 스키마를 참조하세요. |
| 부울 | 옵션 |
순서가 지정된 작업은 연속적으로 실행 . 오류가 발생하면 나머지 작업이 취소됩니다. 순서가 지정되지 않은 작업은 병렬로 실행 됩니다. 오류가 발생하면 나머지 문이 실행 됩니다. 성능 향상을 위해 서버 에서 작업의 순서를 변경할 수 있습니다. 따라서 애플리케이션이 작업 실행 순서에 의존해서는 안 됩니다. 기본값은 |
| 부울 | 옵션 |
기본값은 |
| 문자열 | 옵션 | 선택 사항. 이 명령에 첨부할 사용자 제공 코멘트입니다. 설정되면 이 설명은 다음 위치에서 이 명령의 레코드와 함께 표시됩니다.
댓글은 유효한 모든 BSON types (문자열, 정수, 객체, 배열 등)이 될 수 있습니다. |
| 문서 | 옵션 | 작업에서 참조할 상수 목록이 포함된 문서입니다. |
| 부울 | 옵션 |
기본값은 |
| integer | 옵션 |
|
| non-negative integer | 옵션 | 시간 제한을 밀리초 단위로 지정합니다. MongoDB는 |
| 문자열 | 옵션 | 작업에 대한 우려를 씁니다 . 서버 기본값 을 사용하려면 생략합니다. |
출력
이 명령은 다음 필드가 포함된 문서 를 반환합니다.
필드 | 유형 | 설명 |
|---|---|---|
| 문서 | 명령 결과가 있는 커서입니다. |
| integer | 커서 식별자입니다. |
| 문서 배열 | 작업 결과입니다. |
| integer |
|
| integer |
|
| integer | 오류에 대한 코드 번호입니다. |
| 문자열 | 오류에 대한 설명입니다. |
| 문서 | 오류에 대한 문서 인덱스 키 사양입니다. |
| 문서 | 오류에 대한 문서 인덱스 키 값입니다. |
| integer | 작업의 영향을 받는 문서의 총 개수입니다. |
| integer | 업데이트 작업으로 수정된 문서 수입니다. |
| integer |
|
| integer | 삽입된 문서 수입니다. |
| integer | 일치하는 문서 수입니다. |
| integer | 수정된 문서 수입니다. |
| integer | 업서트된 문서 수입니다. |
| integer | 삭제된 문서 수입니다. |
| integer |
|
참고
출력 필드는 bulkWrite 명령에서 실행 하는 작업에 따라 달라질 수 있습니다.
행동
다중 문서 필드 및 재시도 가능 쓰기
multi 필드 가 true 인 경우 업데이트 또는 삭제 작업은 문서 filter 와 일치하는 모든 문서를 업데이트하거나 삭제합니다. false 인 경우 작업은 filter 문서 와 일치하는 첫 번째 문서 를 업데이트하거나 삭제합니다. 다중 문서 트랜잭션에 대한 자세한 내용은 트랜잭션을 참조하세요 .
재시도 가능 쓰기를 활성화 하려면 재시도 가능 쓰기를 참조 하세요.
재시도 가능 쓰기가 있고 multi 필드 가 true 로 설정하다 상태에서 bulkWrite 삽입 작업을 사용할 수 있습니다.
multi 필드 를 true 로 설정하다 한 상태에서 bulkWrite 업데이트 및 삭제 작업을 사용할 수 있습니다. 그러나 multi 가 true 로 설정하다 되어 있고 재시도 가능 쓰기가 모두 있는 업데이트 또는 삭제 작업은 사용할 수 없습니다.
샤딩된 클러스터의 쓰기 고려(write concern) 오류
버전 8.1.2에서 변경되었습니다.
bulkWrite 이 샤딩된 클러스터의 mongos 에서 실행되면 하나 이상의 다른 오류가 발생하더라도 항상 응답에서 writeConcernError 이 보고됩니다. 이전 릴리스에서는 다른 오류로 인해 bulkWrite 가 쓰기 고려 (write concern) 오류를 보고하지 않는 경우가 있었습니다.
예시 들어, 문서 유효성 검사 실패하여 DocumentValidationFailed 오류를 트리거하고 쓰기 고려 (write concern) 오류도 발생하면 응답의 최상위 필드 에 DocumentValidationFailed 오류와 writeConcernError 가 모두 반환됩니다.
운영 성과
기존 삽입, 업데이트 및 삭제 명령을 bulkWrite 명령으로 다시 작성하고 errorsOnly 을 true 로 설정하다 하면 bulkWrite 명령은 기존 명령과 유사한 성능을 갖습니다. errorsOnly 를 false 로 설정하다 하면 성능이 저하됩니다.
여러 개별 쓰기 (write) 명령을 단일 bulkWrite 명령으로 대체하면 네트워크 지연 시간을 줄여 성능을 향상시킬 수 있습니다. 예를 들어 다음 순서를 고려해 보세요.
insert update delete
이 시퀀스를 단일 bulkWrite 조치로 대체합니다.
{ bulkWrite: 1, ops: [ insert, update, delete ] }
예시
단일 네임스페이스 대량 쓰기 예시
다음 bulkWrite 예시 에서는 단일 네임스페이스 를 수정합니다.
피자 예시 컬렉션 수정
다음 bulkWrite 명령을 실행하여 pizzas 컬렉션 에서 삽입, 업데이트 및 삭제 작업을 수행합니다.
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // Specify the namespace ID index immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo at the end // of the example. // Insert a pizza. { insert: 0, document: { _id: 4, type: "sausage", size: "small", price: 12 } }, // Update the price for medium pizzas. { update: 0, filter: { size: "medium" }, updateMods: { $set: { price: 15 } } }, // Delete the pizza with an _id of 2. { delete: 0, filter: { _id: 2 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ] } )
pizzas 컬렉션 은 기본값 test 데이터베이스 에 있으므로 ns 네임스페이스 는 "test.pizzas" 입니다. 네임스페이스 ID 인덱스 는 0 이며, ops 배열 에서 삽입, 업데이트 및 삭제 작업의 첫 번째 필드 에 설정하다 됩니다.
출력 검사
다양한 ok: 1 필드와 nErrors: 0 가 포함된 다음 bulkWrite 예시 출력은 모든 작업이 성공적인 했음을 나타냅니다.
{ cursor: { id: Long('0'), firstBatch: [ { ok: 1, idx: 0, n: 1 }, { ok: 1, idx: 1, n: 1, nModified: 1 }, { ok: 1, idx: 2, n: 1 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 0, nInserted: 1, nMatched: 1, nModified: 1, nUpserted: 0, nDeleted: 1, ok: 1 }
출력 필드에 대한 자세한 내용은 출력 섹션을 참조하세요.
여러 네임스페이스 대량 쓰기 예시
bulkWrite 명령에 여러 네임스페이스를 지정할 수 있습니다.
다음 bulkWrite 예시 에는 두 네임스페이스에 대한 삽입, 업데이트 및 삭제 작업이 포함되어 있습니다.
피자 예시 컬렉션 만들기
test 데이터베이스 에 pizzas 컬렉션 이 이미 있는 경우 db.collection.drop() 메서드를 사용하여 먼저 컬렉션을 삭제한 후 다음을 실행.
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
피자 주문 예시 컬렉션 만들기
실행:
db.pizzaOrders.insertMany( [ { _id: 0, type: "pepperoni", number: 5, orderDate: new Date( "2023-01-15T12:00:00Z" ) }, { _id: 1, type: "cheese", number: 15, orderDate: new Date( "2023-01-23T11:12:32Z" ) }, { _id: 2, type: "vegan", number: 20, orderDate: new Date( "2023-03-20T10:01:12Z" ) } ] )
예시 컬렉션 수정
다음 bulkWrite 명령을 실행하여 예시 컬렉션에서 삽입, 업데이트 및 삭제 작업을 수행합니다.
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // Specify the namespace ID indexes immediately after // the insert, update, and delete. For example, "insert: 0" // specifies the 0 namespace ID index, which is the "test.pizzas" // namespace. And, "insert: 1" specifies "test.pizzaOrders". // Insert pizzas. // Namespace ID is 0 for "test.pizzas", which // is specified as "insert: 0". { insert: 0, document: { _id: 5, type: "sausage", size: "small", price: 12 } }, { insert: 0, document: { _id: 6, type: "vegan cheese", size: "large", price: 25 } }, // Update the price for cheese pizzas. { update: 0, filter: { type: "cheese" }, updateMods: { $set: { price: 15 } } }, // Delete pizzas with a price less than 7. { delete: 0, filter: { price: { $lt: 7 } } }, // Insert pizza orders. // Namespace ID is 1 for "test.pizzaOrders". { insert: 1, document: { _id: 3, type: "sausage", number: 7, orderDate: new Date( "2023-04-15T12:02:15Z" ) } }, { insert: 1, document: { _id: 4, type: "vegan", number: 16, orderDate: new Date( "2023-05-12T11:03:11Z" ) } }, // Update the number of pizza orders for cheese pizzas. { update: 1, filter: { type: "cheese" }, updateMods: { $set: { number: 50 } } }, // Delete the pizza order with an _id of 2. { delete: 1, filter: { _id: 2 } }, // Delete pizza orders placed before March 15, 2023. { delete: 1, filter: { orderDate: { $lte: ISODate( "2023-03-15T00:00:00Z" ) } } } ], // Namespaces nsInfo: [ { ns: "test.pizzas" }, // Namespace ID index is 0. { ns: "test.pizzaOrders" } // Namespace ID index is 1. ] } )
출력 검사
다음 bulkWrite 예시 출력은 작업이 성공적인 했음을 나타냅니다.
{ cursor: { id: Long('0'), firstBatch: [ { ok: 1, idx: 0, n: 1 }, { ok: 1, idx: 1, n: 1 }, { ok: 1, idx: 2, n: 1, nModified: 1 }, { ok: 1, idx: 3, n: 1 }, { ok: 1, idx: 4, n: 1 }, { ok: 1, idx: 5, n: 1 }, { ok: 1, idx: 6, n: 1, nModified: 1 }, { ok: 1, idx: 7, n: 1 }, { ok: 1, idx: 8, n: 1 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 0, nInserted: 4, nMatched: 2, nModified: 2, nUpserted: 0, nDeleted: 3, ok: 1 }
오류가 있는 작업 대량 쓰기 예시
다음 bulkWrite 예시 에는 오류가 있는 작업과 문서를 변경하지 않는 작업이 포함되어 있습니다.
피자 예시 컬렉션 만들기
test 데이터베이스 에 pizzas 컬렉션 이 이미 있는 경우 db.collection.drop() 메서드를 사용하여 먼저 컬렉션을 삭제한 후 다음을 실행.
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
피자 예시 컬렉션 수정 시도
다음 bulkWrite 명령을 실행하여 pizzas 컬렉션 에서 삽입, 업데이트 및 삭제 작업을 수행합니다.
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // The namespace ID indexes are specified immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo. // Attempt to add a duplicate document with an // _id of 1, which already exists and causes an error. { insert: 0, document: { _id: 1, type: "tomato", size: "small", price: 12 } }, // Attempt to add another duplicate document. { insert: 0, document: { _id: 2, type: "pepper", size: "small", price: 12 } }, // Attempt to change the price for extra large pizzas, // which don't exist. This doesn't cause an error but // doesn't update any documents. { update: 0, filter: { size: "extra large" }, updateMods: { $set: { price: 15 } } }, // Attempt to remove a document that doesn't exist. // This doesn't cause an error but doesn't delete any documents. { delete: 0, filter: { _id: 8 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ], // Set the ordered field to false to run the remaining operations // after an operation returns an error. ordered: false } )
출력 검사
다음 bulkWrite 예시 출력은 오류를 보여줍니다.
{ cursor: { id: Long("0"), firstBatch: [ { ok: 0, idx: 0, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 1 }', keyPattern: { _id: 1 }, keyValue: { _id: 1 }, n: 0 }, { ok: 0, idx: 1, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 2 }', keyPattern: { _id: 1 }, keyValue: { _id: 2 }, n: 0 }, { ok: 1, idx: 2, n: 0, nModified: 0 }, { ok: 1, idx: 3, n: 0 } ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 2, nInserted: 0, nMatched: 0, nModified: 0, nUpserted: 0, nDeleted: 0, ok: 1 }
오류 코드 및 메시지를 포함한 출력 필드에 대한 자세한 내용은 이전 출력 섹션을 참조하세요.
errorsOnly가 활성화된 대량 쓰기 예시
다음 bulkWrite 예시 에서는 errorsOnly 를 true 로 설정하여 오류 출력만 표시합니다.
피자 예시 컬렉션 만들기
test 데이터베이스 에 pizzas 컬렉션 이 이미 있는 경우 db.collection.drop() 메서드를 사용하여 먼저 컬렉션을 삭제한 후 다음을 실행.
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] )
피자 예시 컬렉션 수정 시도
다음 bulkWrite 명령을 실행하여 errorsOnly 가 true 로 설정하다 pizzas 컬렉션 에 대해 삽입, 업데이트 및 삭제 작업을 수행합니다.
db.adminCommand( { bulkWrite: 1, // The ops array contains the insert, update, and delete // operations. ops: [ // The namespace ID indexes are specified immediately after // the insert, update, and delete text. // For example, "insert: 0" specifies the 0 namespace ID index, // which is the "test.pizzas" namespace in nsInfo. // Attempt to add a duplicate document with an // _id of 1, which already exists and causes an error. { insert: 0, document: { _id: 1, type: "tomato", size: "small", price: 12 } }, // Attempt to add another duplicate document. { insert: 0, document: { _id: 2, type: "pepper", size: "small", price: 12 } }, // Attempt to change the price for extra large pizzas, // which don't exist. This doesn't cause an error but // doesn't update any documents. { update: 0, filter: { size: "extra large" }, updateMods: { $set: { price: 15 } } }, // Attempt to remove a document that doesn't exist. // This doesn't cause an error but doesn't delete any documents. { delete: 0, filter: { _id: 8 } } ], // The nsInfo array contains the namespace to apply the // previous operations to. nsInfo: [ { ns: "test.pizzas" } // Namespace ID index is 0. ], // Set the ordered field to false to run the remaining operations // after an operation returns an error. ordered: false, // Set the errorsOnly field to true to only output the errors. errorsOnly: true } )
출력 검사
다음 bulkWrite 예시 출력은 오류를 보여줍니다.
{ cursor: { id: Long("0"), firstBatch: [ { ok: 0, idx: 0, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 1 }', keyPattern: { _id: 1 }, keyValue: { _id: 1 }, n: 0 }, { ok: 0, idx: 1, code: 11000, errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 2 }', keyPattern: { _id: 1 }, keyValue: { _id: 2 }, n: 0 }, ], ns: 'admin.$cmd.bulkWrite' }, nErrors: 2, nInserted: 0, nMatched: 0, nModified: 0, nUpserted: 0, nDeleted: 0, ok: 1 }