개요
이 가이드에서는 복합 작업을 수행하는 방법에 대해 설명합니다.
복합 작업은 읽기 및 쓰기 작업을 단일 작업으로 결합합니다. 읽기 작업과 쓰기 작업을 따로 수행하면 두 작업 사이에 다른 사람이 문서를 변경할 가능성이 있습니다. MongoDB는 복합 작업이 수행되는 동안 수정 중인 문서에 쓰기 잠금을 설정하여 이를 방지합니다.
MongoDB는 다음과 같은 복합 연산을 지원합니다.
팁
한 번에 두 개 이상의 문서 에서 복합 작업을 수행하는 방법을 학습 보려면 트랜잭션 가이드 를 참조하세요.
샘플 데이터
이 가이드의 예시에서는 다음 Course 구조체를 courses collection의 문서 모델로 사용합니다.
type Course struct { Title string Enrollment int32 }
이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db.courses collection에 로드하세요.
coll := client.Database("db").Collection("courses") docs := []interface{}{ Course{Title: "Representation Theory", Enrollment: 40}, Course{Title: "Early Modern Philosophy", Enrollment: 25}, Course{Title: "Animal Communication", Enrollment: 18}, } result, err := coll.InsertMany(context.TODO(), docs)
각 문서에는 각 문서의 title 및 enrollment 필드에 해당하는 과정의 제목 및 최대 등록 수를 비롯한 University 과정에 대한 설명이 포함되어 있습니다.
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.
찾기 및 삭제
FindOneAndDelete() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾아 삭제합니다. 이 메서드는 삭제된 문서가 포함된 SingleResult 을 반환합니다.
참고
FindOneAndDelete() 메서드는 원자 조작이므로 완료될 때까지 다른 쓰기 (write) 작업이 일치하는 문서를 변경하지 못하도록 합니다. DeleteOne() 메서드도 원자 조작이지만 일치하는 문서의 정렬 순서를 지정할 수 없다는 점에서 FindOneAndDelete()과 다릅니다.
별도의 작업으로 문서 찾아 삭제 하려면 FindOne() 메서드를 호출한 다음 DeleteOne() 메서드를 호출합니다.
동작 수정
FindOneAndDeleteOptions를 전달하여 FindOneAndDelete() 메서드의 동작을 수정할 수 있습니다. FindOneAndDeleteOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.
FindOneAndDeleteOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.
메서드 | 설명 |
|---|---|
| The type of language collation to use when sorting results. Default: nil |
| The maximum amount of time that the query can run on the server. Default: nil |
| The fields to include in the document returned. Default: nil |
| The sort fields and directions to order the documents matched. Default: nil |
| The index to use to scan for documents. Default: nil |
예시
다음 예시에서는 FindOneAndDelete() 메서드를 사용하여 enrollment 필드 값이 20보다 작은 첫 번째 문서를 일치시키고 삭제합니다.
filter := bson.D{{"enrollment", bson.D{{"$lt", 20}}}} var deletedDoc Course err := coll.FindOneAndDelete(context.TODO(), filter).Decode(&deletedDoc) if err != nil { panic(err) } res, _ := bson.MarshalExtJSON(deletedDoc, false, false) fmt.Println(string(res))
{"title":"Animal Communication","enrollment":18}
찾기 및 업데이트
FindOneAndUpdate() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾고, 업데이트 문서에 따라 업데이트합니다. 이 메서드는 일치하는 문서가 포함된 SingleResult를 반환합니다.
참고
FindOneAndUpdate() 메서드는 원자 조작이므로 완료될 때까지 다른 쓰기 (write) 작업이 일치하는 문서를 변경하지 못하도록 합니다. UpdateOne() 메서드도 원자 조작이지만 일치하는 문서의 정렬 순서를 지정할 수 없다는 점에서 FindOneAndUpdate()과 다릅니다.
문서를 찾아 별도의 작업으로 업데이트하려면 FindOne() 메서드를 호출한 다음 UpdateOne() 메서드를 호출합니다.
동작 수정
FindOneAndUpdateOptions를 전달하여 FindOneAndUpdate() 메서드의 동작을 수정할 수 있습니다. FindOneAndUpdateOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.
FindOneAndUpdateOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.
메서드 | 설명 |
|---|---|
| The array elements the update applies to. Default: nil |
| Whether to allow the write operation to opt-out of document level validation. Default: false |
| The type of language collation to use when sorting results. Default: nil |
| The maximum amount of time that the query can run on the server. Default: nil |
| The fields to include in the document returned. Default: nil |
| Whether to return the original or updated document in the SingleResult.Default: options.Before |
| The sort fields and directions to order the documents matched. Default: nil |
| Whether to insert a new document if the query filter doesn't match any documents. Default: false |
| The index to use to scan for documents. Default: nil |
예시
다음 예시에서는 FindOneAndUpdate() 메서드를 사용하여 다음 조치를 순서대로 수행합니다.
title필드 값에 'Modern'이 포함된 첫 번째 문서 와 일치합니다.일치하는 문서의
enrollment필드 값을32로 업데이트합니다.업데이트된 문서 반환
filter := bson.D{{"title", bson.D{{"$regex", "Modern"}}}} update := bson.D{{"$set", bson.D{{"enrollment", 32}}}} opts := options.FindOneAndUpdate().SetReturnDocument(options.After) var updatedDoc Course err := coll.FindOneAndUpdate(context.TODO(), filter, update, opts).Decode(&updatedDoc) if err != nil { panic(err) } res, _ := bson.MarshalExtJSON(updatedDoc, false, false) fmt.Println(string(res))
{"title":"Early Modern Philosophy","enrollment":32}
찾기 및 바꾸기
FindOneAndReplace() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾아 대체 문서로 바꿉니다. 이 메서드는 일치하는 문서가 포함된 SingleResult를 반환합니다.
참고
이 메서드는 ReplaceOne() 메서드와 다릅니다. FindOneAndReplace() 는 찾기 및 바꾸기를 단일 작업으로 수행하므로 두 작업 사이에 누군가가 문서 변경할 가능성을 제거합니다. FindOneAndReplace()를 사용하면 일치하는 문서에 정렬 순서를 설정하다 수도 있습니다.
별도의 작업으로 문서 찾아 바꾸려면 FindOne() 메서드를 호출한 다음 ReplaceOne() 메서드를 호출합니다.
동작 수정
FindOneAndReplaceOptions를 전달하여 FindOneAndReplace() 메서드의 동작을 수정할 수 있습니다. FindOneAndReplaceOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.
FindOneAndReplaceOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.
메서드 | 설명 |
|---|---|
| Whether to allow the write operation to opt-out of document level validation. Default: false |
| The type of language collation to use when sorting results. Default: nil |
| The maximum amount of time that the query can run on the server. Default: nil |
| The fields to include in the document returned. Default: nil |
| Whether to return the original or replaced document in the SingleResult.Default: nil |
| The sort fields and directions to order the documents matched. Default: nil |
| Whether to insert a new document if the query filter doesn't match any documents. Default: false |
| The index to use to scan for documents. Default: nil |
예시
다음 예시에서는 FindOneAndReplace() 메서드를 사용하여 다음 조치를 순서대로 수행합니다.
title이 'Representation Theory'인 첫 번째 문서 와 일치합니다.일치하는 문서를
title이 'Combinatorial Theory'이고enrollment가35인 새 문서로 대체합니다.
filter := bson.D{{"title", "Representation Theory"}} replacement := Course{Title: "Combinatorial Theory", Enrollment: 35} var outdatedDoc Course err := coll.FindOneAndReplace(context.TODO(), filter, replacement).Decode(&previousDoc) if err != nil { panic(err) } res, _ := bson.MarshalExtJSON(outdatedDoc, false, false) fmt.Println(string(res))
{"title":"Representation Theory","enrollment":40}
추가 정보
언급된 작업을 수행하는 방법에 대해 자세히 알아보려면 다음 가이드를 참조하세요:
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.