대량 작업
이 페이지의 내용
개요
이 가이드 에서는 Node.js 운전자 사용하여 대량 작업을 수행하는 방법을 학습 수 있습니다. 대량 작업은 서버 에 대한 호출 수를 줄이는 데 도움이 됩니다. 각 작업에 대한 요청 보내는 대신 하나의 조치 내에서 여러 작업을 수행할 수 있습니다.
대량 작업을 사용하여 컬렉션 에 대해 여러 쓰기 (write) 작업을 수행할 수 있습니다. 클라이언트 에서 대량 작업을 실행 여러 네임스페이스에 걸쳐 대량 쓰기를 수행할 수도 있습니다. MongoDB 에서 네임스페이스 <database>.<collection>
형식의 데이터베이스 이름과 컬렉션 이름으로 구성됩니다.
이 가이드에는 다음 섹션이 포함되어 있습니다.
대량 삽입 작업에서는 컬렉션 또는 클라이언트 에서 대량 삽입 작업을 수행하는 방법을 설명합니다.
대량 바꾸기 작업에서는 컬렉션 또는 클라이언트 에서 대량 바꾸기 작업을 수행하는 방법을 설명합니다.
대량 업데이트 작업에서는 컬렉션 또는 클라이언트 에서 대량 업데이트 작업을 수행하는 방법을 설명합니다.
대량 삭제 작업에서는 컬렉션 또는 클라이언트 에서 대량 삭제 작업을 수행하는 방법을 설명합니다.
반환 유형은 대량 쓰기 (write) 작업의 결과로 생성되는 반환 객체 설명합니다.
예외 처리에서는 대량 쓰기 (write) 작업의 작업이 실패할 경우 발생하는 예외에 대해 설명합니다.
추가 정보 에서는 이 가이드 에 언급된 유형 및 메서드에 대한 리소스 및 API 문서 링크를 제공합니다.
중요
서버 및 드라이버 버전 요구 사항
컬렉션 수준 대량 쓰기 (write) 작업에는 다음 버전이 필요합니다.
MongoDB Server 버전 3.2 이상
Node.js 운전자 버전 3.6 이상
클라이언트 수준 대량 쓰기 (write) 작업에는 다음 버전이 필요합니다.
MongoDB Server 버전 8.0 이상
Node.js 운전자 버전 6.10 이상
샘플 데이터
이 가이드 의 예제에서는 movies
users
sample_mflix
Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 및 컬렉션을 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 Atlas 시작하기 가이드 참조하세요.
대량 삽입 작업
대량 삽입 작업을 수행하려면 삽입하려는 각 문서 에 대해 대량 작업 모델을 만듭니다. 그런 다음 이러한 모델 목록을 bulkWrite()
메서드에 전달합니다.
이 섹션에서는 다음 유형의 대량 작업을 수행하는 방법에 대해 설명합니다.
컬렉션 대량 삽입
컬렉션 에서 대량 삽입 작업을 수행하려면 각 작업에 대해 InsertOneModel
을 만듭니다. 그런 다음 컬렉션 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다. InsertOneModel
를 만들려면 모델의 document
필드 지정하고 삽입하려는 문서 로 설정하다 .
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
InsertOneModel
인스턴스 두 개를 지정합니다. 각InsertOneModel
는sample_mflix
데이터베이스 의movies
컬렉션 에 삽입할 문서 나타냅니다.movies
컬렉션 에서bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.삽입된 문서 수를 인쇄합니다.
const insertModels = [{ insertOne: { document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } } }, { insertOne: { document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } } }]; const insertResult = await movies.bulkWrite(insertModels); console.log(`Inserted documents: ${insertResult.insertedCount}`);
Inserted documents: 2
클라이언트 대량 삽입
여러 컬렉션 또는 데이터베이스에 걸쳐 대량 삽입 작업을 수행하려면 각 작업에 대해 ClientBulkWriteModel
을 만듭니다. 그런 다음 클라이언트 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.
다음 표에서는 삽입 작업을 지정하기 위해 ClientBulkWriteModel
에 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The namespace in which to insert a document. Type: String |
| The operation you want to perform. For insert operations,
set this field to "insertOne" .Type: String |
| The document to insert. Type: Document |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에 있는 세 개의
ClientBulkWriteModel
인스턴스를 지정합니다. 처음 두 모델은movies
컬렉션 에 삽입할 문서를 나타내고, 마지막 모델은users
컬렉션 에 삽입할 문서 나타냅니다.클라이언트 에서
bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.삽입된 문서 수를 인쇄합니다.
const clientInserts = [{ namespace: "sample_mflix.movies", name: "insertOne", document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } }, { namespace: "sample_mflix.movies", name: "insertOne", document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } }, { namespace: "sample_mflix.users", name: "insertOne", document: { name: "Brian Schwartz", email: "bschwartz@example.com" } }]; const clientInsertRes = await client.bulkWrite(clientInserts); console.log(`Inserted documents: ${clientInsertRes.insertedCount}`);
Inserted documents: 3
대량 교체 작업
대량 교체 작업을 수행하려면 교체하려는 각 문서 에 대해 대량 작업 모델을 만듭니다. 그런 다음 이러한 모델 목록을 bulkWrite()
메서드에 전달합니다.
이 섹션에서는 다음 유형의 대량 작업을 수행하는 방법에 대해 설명합니다.
컬렉션 대량 교체
컬렉션 에서 대량 바꾸기 작업을 수행하려면 각 작업에 대해 ReplaceOneModel
을 만듭니다. 그런 다음 컬렉션 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.
다음 표에서는 ReplaceOneModel
에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Bson |
| (Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false .Type: Boolean |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
ReplaceOneModel
인스턴스 두 개를 지정합니다.ReplaceOneModel
인스턴스에는movies
컬렉션 의 영화를 나타내는 문서를 대체하는 지침이 포함되어 있습니다.movies
컬렉션 에서bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.수정된 문서 수를 인쇄합니다.
const replaceOperations = [{ replaceOne: { filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" }, upsert: false } }, { replaceOne: { filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" }, upsert: false } }]; const replaceResult = await movies.bulkWrite(replaceOperations); console.log(`Modified documents: ${replaceResult.modifiedCount}`);
Modified documents: 2
클라이언트 대량 교체
여러 컬렉션 또는 데이터베이스에서 대량 바꾸기 작업을 수행하려면 각 작업에 대해 ClientBulkWriteModel
을 만듭니다. 그런 다음 클라이언트 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.
다음 표에서는 대체 작업을 지정하기 위해 ClientBulkWriteModel
에 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The namespace in which to replace a document. Type: String |
| The operation you want to perform. For replace operations,
set this field to "replaceOne" .Type: String |
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Bson |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에 있는 세 개의
ClientBulkWriteModel
인스턴스를 지정합니다. 처음 두 모델에는movies
컬렉션 에 있는 문서에 대한 교체 지침이 포함되어 있고, 마지막 모델에는users
컬렉션 에 있는 문서 에 대한 교체 지침이 포함되어 있습니다.클라이언트 에서
bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.수정된 문서 수를 인쇄합니다.
const clientReplacements = [{ namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" } }, { namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" } }, { namespace: "sample_mflix.users", name: "replaceOne", filter: { name: "April Cole" }, replacement: { name: "April Franklin", email: "aprilfrank@example.com" } }]; const clientReplaceRes = await client.bulkWrite(clientReplacements); console.log(`Modified documents: ${clientReplaceRes.modifiedCount}`);
Modified documents: 3
대량 업데이트 작업
대량 업데이트 작업을 수행하려면 수행하려는 각 업데이트 에 대한 대량 작업 모델을 생성합니다. 그런 다음 이러한 모델 목록을 bulkWrite()
메서드에 전달합니다.
이 섹션에서는 다음 유형의 대량 작업을 수행하는 방법에 대해 설명합니다.
컬렉션 일괄 업데이트
컬렉션 에서 일괄 업데이트 작업을 수행하려면 각 작업에 대해 UpdateOneModel
또는 UpdateManyModel
를 만듭니다. 그런 다음 컬렉션 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다. UpdateOneModel
은 필터하다 와 일치하는 하나 문서 만 업데이트하고 UpdateManyModel
는 필터하다 와 일치하는 모든 문서를 업데이트합니다.
다음 표에서는 UpdateOneModel
또는 UpdateManyModel
에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The filter that matches one or more documents you want to update. When
specified in an UpdateOneModel , only the first matching document will
be updated. When specified in an UpdateManyModel , all matching documents
will be updated.Type: Document |
| The update to perform. Type: Document |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Array |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: String or Object |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
UpdateOneModel
및UpdateManyModel
인스턴스 지정합니다. 이러한 모델에는movies
컬렉션 의 영화를 나타내는 문서를 업데이트 위한 지침이 포함되어 있습니다.movies
컬렉션 에서bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.수정된 문서 수를 인쇄합니다.
const updateOperations = [{ updateOne: { filter: { title: "Interstellar" }, update: { $set: { title: "Interstellar Updated", genre: "Sci-Fi Adventure" } }, upsert: true } }, { updateMany: { filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } } } }]; const updateResult = await movies.bulkWrite(updateOperations); console.log(`Modified documents: ${updateResult.modifiedCount}`);
Modified documents: 2320
클라이언트 일괄 업데이트
여러 컬렉션 또는 데이터베이스에서 일괄 업데이트 작업을 수행하려면 각 작업에 대해 ClientBulkWriteModel
을 만듭니다. 그런 다음 클라이언트 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.
다음 표에서는 ClientBulkWriteModel
에 설정하다 업데이트 작업을 지정할 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The namespace in which to update a document. Type: String |
| The operation you want to perform. For update operations,
set this field to "updateOne" or "updateMany" .Type: String |
| The filter that matches one or more documents you want to update. If
you set the model name to "updateOne" , only the first matching
document is updated. If you set name to "updateMany" , all
matching documents are updated.Type: Document |
| The updates to perform. Type: Document or Document[] |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Document[] |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Document or String |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
ClientBulkWriteModel
인스턴스 두 개를 지정합니다. 첫 번째 모델은movies
컬렉션 에 대해 하나의 업데이트 작업을 지정하고, 두 번째 모델은users
컬렉션 에 대해 하나의 업데이트 작업을 지정합니다.클라이언트 에서
bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.수정된 문서 수를 인쇄합니다.
const clientUpdates = [{ namespace: "sample_mflix.movies", name: "updateMany", filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } }, upsert: false }, { namespace: "sample_mflix.users", name: "updateOne", filter: { name: "Jon Snow" }, update: { $set: { name: "Aegon Targaryen", email: "targaryen@example.com" } }, upsert: false }]; const clientUpdateRes = await client.bulkWrite(clientUpdates); console.log(`Modified documents: ${clientUpdateRes.modifiedCount}`);
Modified documents: 2320
대량 삭제 작업
대량 삭제 작업을 수행하려면 각 삭제 작업에 대한 대량 작업 모델을 만듭니다. 그런 다음 이러한 모델 목록을 bulkWrite()
메서드에 전달합니다.
이 섹션에서는 다음 유형의 대량 작업을 수행하는 방법에 대해 설명합니다.
컬렉션 대량 삭제
컬렉션 에서 일괄 삭제 작업을 수행하려면 각 작업에 대해 DeleteOneModel
또는 DeleteManyModel
를 만듭니다. 그런 다음 컬렉션 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다. DeleteOneModel
은 필터하다 와 일치하는 문서 하나만 삭제하고 DeleteManyModel
는 필터하다 와 일치하는 모든 문서를 삭제합니다.
다음 표에서는 DeleteOneModel
또는 DeleteManyModel
에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The filter that matches one or more documents you want to delete. When
specified in a DeleteOneModel , only the first matching document will
be deleted. When specified in a DeleteManyModel , all matching documents
will be deleted.Type: Document |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: String or Object |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
DeleteOneModel
및DeleteManyModel
인스턴스 를 지정합니다. 이러한 모델에는movies
컬렉션 에서 문서를 삭제 하는 지침이 포함되어 있습니다.movies
컬렉션 에서bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.삭제된 문서 수를 인쇄합니다.
const deleteOperations = [{ deleteOne: { filter: { title: "Dunkirk" } } }, { deleteMany: { filter: { rated: "R" } } }]; const deleteResult = await movies.bulkWrite(deleteOperations); console.log(`Deleted documents: ${deleteResult.deletedCount}`);
Deleted documents: 5538
클라이언트 대량 삭제
여러 컬렉션 또는 데이터베이스에서 일괄 삭제 작업을 수행하려면 각 작업에 대해 ClientBulkWriteModel
을 만듭니다. 그런 다음 클라이언트 에서 bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.
다음 표에서는 삭제 작업을 지정하기 위해 ClientBulkWriteModel
에 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| The namespace in which to delete a document. Type: String |
| The operation you want to perform. For delete operations,
set this field to "deleteOne" or "deleteMany" .Type: String |
| The filter that matches one or more documents you want to delete. If
you set the model name to "deleteOne" , only the first matching
document is deleted. If you set name to "deleteMany" , all
matching documents are deleted.Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Document or String |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Document |
예시
이 예에서는 다음 조치를 수행합니다.
배열 에
ClientBulkWriteModel
인스턴스 두 개를 지정합니다. 첫 번째 모델은movies
컬렉션 에 대해 하나의 삭제 작업을 지정하고, 두 번째 모델은users
컬렉션 에 대해 하나의 삭제 작업을 지정합니다.클라이언트 에서
bulkWrite()
메서드를 호출하고 모델 배열 매개 변수로 전달합니다.수정된 문서 수를 인쇄합니다.
const clientDeletes = [{ namespace: "sample_mflix.movies", name: "deleteMany", filter: { rated: "R" } }, { namespace: "sample_mflix.users", name: "deleteOne", filter: { email: "emilia_clarke@gameofthron.es" } }]; const clientDeleteRes = await client.bulkWrite(clientDeletes); console.log(`Deleted documents: ${clientDeleteRes.deletedCount}`);
Deleted documents: 5538
반환 유형
BulkWriteResult
Collection.bulkWrite()
메서드는 대량 작업에 대한 정보를 제공하는 BulkWriteResult
객체 반환합니다.
다음 표에서는 BulkWriteResult
객체 의 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| 삽입된 문서 수 |
| 일치하는 문서 수 |
| 업데이트된 문서 수 |
| 업서트된 문서 수 |
| 삭제된 문서 수 |
ClientBulkWriteResult
MongoClient.bulkWrite()
메서드는 클라이언트 대량 쓰기 (write) 작업에 대한 정보가 포함된 ClientBulkWriteResult
객체 반환합니다.
다음 표에서는 ClientBulkWriteResult
객체 의 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| 대량 쓰기 (write) 승인되었는지 여부를 나타내는 부울 값 |
| 삽입된 문서 수 |
| 일치하는 문서 수 |
| 업데이트된 문서 수 |
| 업서트된 문서 수 |
| 삭제된 문서 수 |
| 성공적인 각 개별 삽입 작업의 결과 |
| 성공적인 각 개별 업데이트 작업의 결과 |
| 각 개별 성공적인 삭제 작업의 결과 |
예외 처리
컬렉션 대량 쓰기 예외
컬렉션 에서 호출된 대량 쓰기 (write) 작업이 실패하면 Node.js 운전자 MongoBulkWriteError
을 발생시키고 ordered
옵션이 true
로 설정하다 경우 추가 작업을 수행하지 않습니다. ordered
을(를) false
(으)로 설정하다 하면 후속 작업을 계속 시도합니다.
팁
순서가 지정된 대량 작업과 순서가 지정되지 않은 대량 작업에 대해 자세히 학습 MongoDB Server 매뉴얼의 대량 쓰기 가이드 에서 순서가 지정된 작업과 순서가 지정되지 않은 작업 섹션을 참조하세요.
MongoBulkWriteError
객체 에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
---|---|
| The error message. Type: String |
| An array of errors that occurred during the bulk write operation. Type: BulkWriteError[] |
| Write concern errors that occurred during execution of the bulk write operation. Type: WriteConnectionError[] |
| The results of any successful operations performed before the exception was
thrown. Type: BulkWriteResult[] |
| The underlying error object, which may contain more details. Type: Error |
클라이언트 대량 쓰기 예외
클라이언트 에서 호출된 대량 쓰기 (write) 작업이 실패하면 Node.js 운전자 MongoClientBulkWriteError
를 생성합니다. 기본값 으로 운전자 오류 발생 후 후속 작업을 수행하지 않습니다. ordered
옵션을 bulkWrite()
메서드에 전달하고 false
로 설정하다 운전자 나머지 작업을 계속 시도합니다.
MongoClientBulkWriteError
객체 에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
---|---|
| An array of documents specifying each write concern error. Type: Document[] |
| An map of errors that occurred during individual write operations. Type: Map<number, ClientBulkWriteError> |
| The partial result of the client bulk write that reflects the operation's
progress before the error. Type: ClientBulkWriteResult |
추가 정보
대량 작업에 대해 자세히 학습 MongoDB Server 매뉴얼에서 대량 쓰기 작업을 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.