문서의 배열 업데이트
개요
이 가이드에서는 하나 이상의 문서에서 배열 요소를 업데이트하는 방법을 학습할 수 있습니다.
배열의 요소를 업데이트하려면 다음 작업을 수행하세요.
업데이트를 지정하는 업데이트업데이트 문서 제공합니다.
업데이트할 배열 요소를 지정합니다.
이러한 사양으로 업데이트 작업을 사용하여 업데이트를 수행합니다.
샘플 데이터
이 가이드의 예시에서는 다음 Drink
구조체를 drinks
collection의 문서 모델로 사용합니다.
type Drink struct { Description string Sizes []int32 `bson:"sizes,truncate"` Styles []string }
truncate
구조체 태그를 사용하면 드라이버가 마샬링을 해제할 때 float64
와(과) 같은 유형을 int32
(으)로 자를 수 있습니다.
이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db.drinks
collection에 로드하세요.
coll := client.Database("db").Collection("drinks") docsToInsert := []interface{}{ Drink{Description: "Matcha Latte", Sizes: []int32{12, 16, 20}, Styles: []string{"iced", "hot", "extra hot"}}, } result, err := coll.InsertMany(context.TODO(), docsToInsert)
각 문서에는 각 문서의 description
, sizes
및 styles
필드에 해당하는 음료 설명, 음료의 크기(온스), 제조 방식을 비롯한 음료 설명이 포함되어 있습니다.
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.
다음 예시에서는 FindOneAndUpdate()
메서드를 사용하여 문서를 검색 및 업데이트하고 업데이트가 발생한 후의 문서의 상태를 반환합니다. 배열 필드가 있는 여러 문서를 업데이트하려면 UpdateMany()
메서드를 사용하세요.
배열 요소 지정
업데이트할 배열 요소를 지정하려면 위치 연산자를 사용합니다. 위치 연산자는 업데이트할 첫 번째, 여러 개 또는 모든 배열 요소를 지정할 수 있습니다.
위치 연산자를 사용해 배열 요소를 지정할 때는 점 표기법을 사용합니다. 점 표기법은 내장된 문서의 배열 요소와 필드를 탐색하기 위한 속성 액세스 구문입니다.
첫 번째 배열 요소
쿼리 필터와 일치하는 첫 번째 배열 요소를 업데이트하려면 위치 $
연산자를 사용합니다. 쿼리 필터는 배열 필드에 대한 필터여야 합니다.
예시
이 예에서는 다음 조치를 수행합니다.
값은
16
보다 작거나 같은sizes
의 배열 요소와 일치합니다.일치하는 첫 번째 배열 값을
2
만큼 감소시킵니다.
filter := bson.D{{"sizes", bson.D{{"$lte", 16}}}} update := bson.D{{"$inc", bson.D{{"sizes.$", -2}}}} opts := options.FindOneAndUpdate(). SetReturnDocument(options.After) // Updates the first document that matches the filter var updatedDoc Drink err := coll.FindOneAndUpdate(context.TODO(), filter, update, opts). Decode(&updatedDoc) if err != nil { panic(err) } // Prints the updated document res, _ := bson.MarshalExtJSON(updatedDoc, false, false) fmt.Println(string(res))
{"description":"Matcha Latte","sizes":[10,16,20],"styles":["iced","hot","extra hot"]}
참고
앞의 예시 에서 쿼리 필터하다 12
및 16
값과 일치합니다. 작업은 12
와 먼저 일치하므로 업데이트 의 대상입니다. 일치하는 두 값을 모두 업데이트 방법을 학습 다중 배열 요소 항목을 참조하세요.
다중 배열 요소
쿼리 필터와 일치하는 여러 배열 요소를 업데이트하려면 필터링된 위치 $[<identifier>]
연산자를 사용합니다. 업데이트할 배열 요소를 지정하려면 업데이트 작업에 배열 필터를 포함해야 합니다.
<identifier>
는 배열 필터 내에서 사용하는 이름입니다. 이 값은 소문자로 시작해야 하며 영숫자만 포함할 수 있습니다.
예시
이 예에서는 다음 조치를 수행합니다.
"hot"
문자열이 포함된 배열 요소와 일치하도록hotOptions
이라는 식별자를 사용하여 배열 필터하다 만듭니다.FindOneAndUpdateOptions
인스턴스 만들 때SetArrayFilters()
메서드를 사용하여 배열 필터하다 적용합니다.FindOneAndUpdate()
메서드를 사용하여 이러한 배열 요소의 값을 제거합니다.
identifier := []interface{}{bson.D{{"hotOptions", bson.D{{"$regex", "hot"}}}}} update := bson.D{{"$unset", bson.D{{"styles.$[hotOptions]", ""}}}} opts := options.FindOneAndUpdate(). SetArrayFilters(identifier). SetReturnDocument(options.After) // Updates the first document that matches the filter var updatedDoc Drink err := coll.FindOneAndUpdate(context.TODO(), bson.D{}, update, opts). Decode(&updatedDoc) if err != nil { panic(err) } // Prints the updated document res, _ := bson.MarshalExtJSON(updatedDoc, false, false) fmt.Println(string(res))
{"description":"Matcha Latte","sizes":[12,16,20],"styles":["iced","",""]}
모든 배열 요소
모든 배열 요소를 업데이트하려면 모든 위치 $[]
연산자를 사용하세요.
참고
배열 필드에 쿼리 필터를 지정하면 위치 $[]
연산자는 쿼리 필터를 무시하고 모든 배열 요소를 업데이트합니다.
예시
이 예시에서는 sizes
의 모든 배열 요소에 29.57
을 곱해 온스를 밀리리터로 변환합니다.
identifier := []interface{}{bson.D{{"hotOptions", bson.D{{"$regex", "hot"}}}}} update := bson.D{{"$unset", bson.D{{"styles.$[hotOptions]", ""}}}} opts := options.FindOneAndUpdate(). SetArrayFilters(identifier). SetReturnDocument(options.After) // Updates the first document that matches the filter var updatedDoc Drink err := coll.FindOneAndUpdate(context.TODO(), bson.D{}, update, opts). Decode(&updatedDoc) if err != nil { panic(err) } // Prints the updated document res, _ := bson.MarshalExtJSON(updatedDoc, false, false) fmt.Println(string(res))
{"description":"Matcha Latte","sizes":[354,473,591],"styles":["iced","hot","extra hot"]}
추가 정보
이 가이드에서 설명하는 작업에 대해 자세히 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.