Docs Menu
Docs Home
/
MongoDB 매뉴얼
/ / /

bulkWrite

이 페이지의 내용

  • 정의
  • 구문
  • 명령 필드
  • 출력
  • 행동
  • 예제
  • 자세히 알아보기
bulkWrite

버전 8.0에 추가 되었습니다.

MongoDB 8.0 부터는 새로운 bulkWrite 명령을 사용하여 한 번의 요청 으로 여러 컬렉션에 대한 많은 삽입, 업데이트 및 삭제 작업을 수행할 수 있습니다. 기존 db.collection.bulkWrite() 메서드에서는 한 번의 요청 으로 하나의 컬렉션 만 수정할 수 있습니다.

bulkWrite 명령에서 각 컬렉션 을 지정하려면 네임스페이스 (데이터베이스 및 컬렉션 이름)를 사용합니다.

명령의 구문은 다음과 같습니다.

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: <bolean>,
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> },
writeConcern: <string>
} )

명령 구문에서 여러 개를 지정할 수 있습니다.

  • ops 배열 에서 임의의 순서로 삽입, 업데이트 및 삭제 작업을 수행할 수 있습니다.

  • nsInfo 배열 의 작업에 대한 네임스페이스입니다. 작업을 네임스페이스 와 일치시키려면 동일한 네임스페이스 ID 인덱스 를 사용합니다. 인덱스는 0 부터 시작합니다. 샤딩된 컬렉션을 사용할 수 있습니다.

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

필드
유형
필요성
설명
insert
integer
필수 사항
삽입 작업의 네임스페이스 ID 인덱스 로, nsInfo 배열 의 ns 필드 에 있는 네임스페이스 ID 인덱스 와 일치해야 합니다. 인덱스는 0 부터 시작합니다.
document
문서
필수 사항
컬렉션 에 삽입할 문서입니다.
update
integer
필수 사항
업데이트 작업의 네임스페이스 ID 인덱스 로, nsInfo 배열 의 ns 필드 에 있는 네임스페이스 ID 인덱스 와 일치해야 합니다. 인덱스는 0 부터 시작합니다.
filter
문서
옵션
쿼리 선택기 를 사용하여 업데이트 또는 삭제 작업에 필요한 문서를 제한할 수 있습니다.
updateMods
문서
옵션

컬렉션 에서 수행할 업데이트 작업입니다. 다음 중 하나를 지정할 수 있습니다.

arrayFilters
문서 배열
옵션

배열 필드 에 대한 업데이트 작업을 위해 수정할 문서를 지정하는 필터하다 문서의 배열입니다.

자세한 내용 arrayFilters 를 사용한 배열 업데이트 작업을 참조하세요.

multi
부울
옵션

multi 필드 가 true 인 경우 업데이트 또는 삭제 작업은 문서 filter 와 일치하는 모든 문서를 업데이트하거나 삭제합니다. false 인 경우 작업은 filter 문서 와 일치하는 첫 번째 문서 를 업데이트하거나 삭제합니다. 다중 문서 트랜잭션에 대한 자세한 내용은 트랜잭션을 참조하세요 .

기본값은 false입니다.

hint
문서
옵션
문서 filter 에 사용할 인덱스 입니다. 인덱스 가 존재하지 않으면 업데이트 작업은 오류를 반환합니다.
constants
문서
옵션
집계 파이프라인 사용자 지정 업데이트 에 대한 상수입니다.
collation
문서
옵션
업데이트 또는 삭제 작업을 위한 데이터 정렬 입니다.
delete
integer
필수 사항
삭제 작업의 네임스페이스 ID 인덱스 로, nsInfo 배열 의 ns 필드 에 있는 네임스페이스 ID 인덱스 와 일치해야 합니다. 인덱스는 0 부터 시작합니다.
ns
문자열
필수 사항
작업을 위한 네임스페이스(데이터베이스 및 컬렉션)입니다. ops 의 각 작업에 대한 네임스페이스 ID 인덱스 를 ns 의 일치하는 네임스페이스 배열 인덱스 로 설정합니다. 인덱스는 0 부터 시작합니다.
collectionUUID
문자열
옵션
작업에 대한 컬렉션 을 지정하는 UUID 16진수 값입니다.
encryptionInformation
문서
옵션
작업에 대한 암호화 정보 스키마 및 토큰입니다. 자세한 내용은 암호화 스키마를 참조하세요.
ordered
부울
옵션

true 인 경우 순서가 지정된 작업을 수행합니다. 그렇지 않으면 순서가 지정되지 않은 작업을 수행합니다.

순서가 지정된 작업은 연속적으로 실행 됩니다. 오류가 발생하면 나머지 작업이 취소됩니다.

순서가 지정되지 않은 작업은 병렬로 실행 됩니다. 오류가 발생하면 나머지 문이 실행 됩니다. 성능 향상을 위해 서버 에서 작업의 순서를 변경할 수 있습니다. 따라서 애플리케이션이 작업 실행 순서에 의존해서는 안 됩니다.

기본값은 true입니다.

bypassDocumentValidation
부울
옵션

true 이면 작업이 문서 유효성 검사 규칙 을 우회합니다. false 인 경우 문서가 유효해야 합니다.

기본값은 false입니다.

comment
문자열
옵션

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

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

let
문서
옵션
작업에서 참조할 상수 목록이 포함된 문서입니다. let 예제 let 옵션 또는 c 필드 에서 변수 사용 및 let 에서 변수 사용을 참조하세요.
errorsOnly
부울
옵션

true 인 경우 작업은 오류만 반환하고 다른 출력은 생략합니다.

기본값은 false입니다.

cursor batchSize
integer
옵션
bulkWrite 명령의 반환 결과에 대한 커서 배치 크기입니다. 자세한 내용은 cursor.batchSize() 를 참조하세요.
writeConcern
문자열
옵션
작업에 대한 우려를 씁니다 . 서버 기본값 을 사용하려면 생략합니다.

이 명령은 다음 필드가 포함된 문서 를 반환합니다.

필드
유형
설명
cursor
문서
명령 결과가 있는 커서입니다.
cursor.id
integer
커서 식별자입니다.
cursor.firstBatch
문서 배열
작업 결과입니다.
cursor.firstBatch.ok
integer
1 는 작업이 성공적인 했음을 나타냅니다. 그렇지 않으면 0.
cursor.firstBatch.idx
integer
ops 배열 의 작업에 해당하는 작업 인덱스 번호입니다. 첫 번째 작업의 idx 값은 0 입니다.
cursor.firstBatch.code
integer
오류에 대한 코드 번호입니다.
cursor.firstBatch.errmsg
문자열
오류에 대한 설명입니다.
cursor.firstBatch.keyPattern
문자열
오류에 대한 문서 인덱스 키 사양입니다.
cursor.firstBatch.keyValue
문자열
오류에 대한 문서 인덱스 키 값입니다.
cursor.firstBatch.n
integer
작업의 영향을 받는 문서의 총 개수입니다.
cursor.firstBatch.nModified
integer
업데이트 작업으로 수정된 문서 수입니다.
nErrors
integer
bulkWrite 명령의 오류 수입니다.
nInserted
integer
삽입된 문서 수입니다.
nMatched
integer
일치하는 문서 수입니다.
nModified
integer
수정된 문서 수입니다.
nUpserted
integer
업서트된 문서 수입니다.
nDeleted
integer
삭제된 문서 수입니다.
ok
integer
1 bulkWrite 명령이 성공적인 했음을 나타냅니다. 그렇지 않으면 0.

참고

출력 필드는 bulkWrite 명령에서 실행 하는 작업에 따라 달라질 수 있습니다.

이 섹션에서는 bulkWrite 명령 동작에 대해 설명합니다.

multi 필드 가 true 인 경우 업데이트 또는 삭제 작업은 문서 filter 와 일치하는 모든 문서를 업데이트하거나 삭제합니다. false 인 경우 작업은 filter 문서 와 일치하는 첫 번째 문서 를 업데이트하거나 삭제합니다. 다중 문서 트랜잭션에 대한 자세한 내용은 트랜잭션을 참조하세요 .

재시도 가능 쓰기를 활성화 하려면 재시도 가능 쓰기를 참조 하세요.

재시도 가능 쓰기가 있고 multi 필드 가 true 로 설정하다 상태에서 bulkWrite 삽입 작업을 사용할 수 있습니다.

multi 필드 를 true 로 설정하다 한 상태에서 bulkWrite 업데이트 및 삭제 작업을 사용할 수 있습니다. 그러나 multitrue 로 설정하다 되어 있고 재시도 가능 쓰기가 모두 있는 업데이트 또는 삭제 작업은 사용할 수 없습니다.

기존 삽입, 업데이트 및 삭제 명령을 bulkWrite 명령으로 다시 작성하고 errorsOnlytrue 로 설정하다 하면 bulkWrite 명령은 기존 명령과 유사한 성능을 갖습니다. errorsOnlyfalse 로 설정하다 하면 성능이 저하됩니다.

또한 다음과 같은 명령 시퀀스가 있는 경우:

insert
update
delete

이러한 명령을 다음 예시 조각으로 바꾸면 다른 옵션에 관계없이 다음 조각이 있는 명령이 더 빠릅니다.

{
bulkWrite: 0,
ops: [
insert,
update,
delete
]
}

성능 향상의 대부분은 네트워크 지연 시간 때문에 발생하며, 이는 구현 에 따라 다르지만 이 예시 는 항상 더 빠릅니다.

이 섹션에는 bulkWrite 명령 예제가 포함되어 있습니다.

다음 bulkWrite 예시 에서는 단일 네임스페이스 를 수정합니다.

1

실행:

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 }
] )
2

다음 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 배열 에서 삽입, 업데이트 및 삭제 작업의 첫 번째 필드 에 설정하다 됩니다.

3

다양한 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 예시 에는 두 네임스페이스에 대한 삽입, 업데이트 및 삭제 작업이 포함되어 있습니다.

1

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 }
] )
2

실행:

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" ) }
] )
3

다음 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.
]
} )
4

다음 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 예시 에는 오류가 있는 작업과 문서를 변경하지 않는 작업이 포함되어 있습니다.

1

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 }
] )
2

다음 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
} )
3

다음 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
}

오류 코드 및 메시지를 포함한 출력 필드에 대한 자세한 내용은 이전 출력 섹션을 참조하세요.

다음 bulkWrite 예시 에서는 errorsOnlytrue 로 설정하여 오류 출력만 표시합니다.

1

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 }
] )
2

다음 bulkWrite 명령을 실행하여 errorsOnlytrue 로 설정하다 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
} )
3

다음 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
}

돌아가기

autoCompact