문서 메뉴
문서 홈
/ / /
Go 드라이버
/ /

문서 교체하기

ReplaceOne() 메서드를 사용하여 collection의 문서를 바꿀 수 있습니다.

이 예제를 실행하는 방법을 알아보려면 사용 예제 를 읽어보세요.

이 예제에서는 restaurants 컬렉션의 문서에 대한 모델로 다음 Restaurant 구조체를 사용합니다:

type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}

omitempty struct 태그 는 비어 있을 때 삽입된 문서에서 해당 필드를 생략합니다.

이 예시에서는 restaurants 컬렉션에서 다음 조치를 수행합니다.

  • name(이)가 'Madame Vo'인 문서와 일치합니다.

  • 일치하는 문서를 새 문서로 바꿉니다.

coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"name", "Madame Vo"}}
// Creates a new document containing "Name" and "Cuisine" fields
replacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"}
// Replaces the first document that matches the filter with a new document
result, err := coll.ReplaceOne(context.TODO(), filter, replacement)
if err != nil {
panic(err)
}

실행 가능한 예시 보기

전체 예시를 실행한 후 restaurants 컬렉션에서 다음과 같이 대체된 문서를 찾을 수 있습니다.

{
"_id" : ObjectId("..."),
"name" : "Monsieur Vo",
"cuisine" : "Asian Fusion"
}

문서를 찾는 방법에 대한 예시는 문서 찾기 사용 예시를 참조하세요.

문서 대체, 쿼리 필터 지정 및 잠재적 오류 처리에 대해 자세히 알아보려면 문서 수정을 참조하세요.

ReplaceOne()

← 여러 문서 업데이트하기