AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

문서 교체

이 가이드 에서는 고 (Go) 운전자 사용하여 MongoDB 컬렉션 의 문서 에서 바꾸기 작업을 수행하는 방법을 학습 수 있습니다. 바꾸기 작업은 업데이트 작업과 다르게 수행됩니다. 업데이트 작업은 대상 문서 에서 지정된 필드만 수정합니다. 바꾸기 작업은 대상 문서 의 모든 필드를 제거하고 새 필드로 바꿉니다.

ReplaceOne() 은 기존 문서를 대체하려는 문서인 대체 문서 를 기대합니다. 대체 문서는 다음과 같은 포맷을 사용합니다.

bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... }

ReplaceOne() 작업이 성공하면 대체 작업에 대한 정보가 포함된 UpdateResult 유형을 반환합니다. UpdateResult 유형에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

MatchedCount

필터하다 와 일치하는 문서 수

ModifiedCount

작업으로 수정된 문서 수입니다.

UpsertedCount

작업에 의해 업서트된 문서 수입니다.

UpsertedID

업서트된 문서의 _id(아무 것도 없는 경우 nil)

여러 문서가 ReplaceOne()에 전달된 쿼리 필터와 일치하는 경우 메서드는 일치하는 첫 번째 문서를 선택하여 대체합니다. 쿼리 필터와 일치하는 문서가 없는 경우 바꾸기 작업이 실패합니다.

다음 문서에서는 주방 용품에 대해 설명합니다.

{ "_id" : 2056, "item" : "Mug", "brand" : "Simply Ceramics", "price" : 2.99, "material" : "Glass"}

다음 예시에서는 ReplaceOne() 메서드를 사용하여 이 문서를 값이 'Cup'인 item 필드와 값이 107인 quantity 필드를 포함하는 문서로 대체합니다.

filter := bson.D{{"_id", 2056}}replacement := bson.D{{"item", "Cup"}, {"quantity", 107}} result, err := collection.ReplaceOne(context.TODO(), filter, replacement)fmt.Printf("Documents matched: %v\n", result.MatchedCount)fmt.Printf("Documents replaced: %v\n", result.ModifiedCount)

대체된 문서에는 다음과 같이 대체 문서의 내용과 변경할 수 없는 _id 필드 등이 있습니다.

{ "_id" : 2056, "item" : "Cup", "quantity" : 107}

참고

설정 예시

이 예는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스 연결에 대해 자세히 알아보려면 MongoClient 만들기를 참조하세요. 이 예시에서는 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스의 restaurants 컬렉션도 사용합니다. Atlas 시작하기의 단계에 따라 MongoDB Atlas의 무료 클러스터에서 데이터베이스에 로드할 수 있습니다.

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

  • name 값이 "Rizzo's Fine Pizza"인 문서 와 일치합니다.

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

// Replaces the first document that matches a filter by using the Go driverpackage main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options") type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` Cuisine string `bson:"cuisine,omitempty"` Address any `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []any `bson:"grades,omitempty"`} func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"name", "Rizzo's Fine Pizza"}} // Creates a new document containing "Name" and "Cuisine" fields replacement := Restaurant{Name: "Rizzo's Pizza", Cuisine: "Pizza/American"} // 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) } // Prints the number of modified documents if result.MatchedCount != 0 { fmt.Println("Number of documents replaced:", result.ModifiedCount) } // When you run this file for the first time, it should print: // Number of documents replaced: 1}

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

{ "_id" : ObjectId("..."), "name" : "Rizzo's Pizza", "cuisine" : "Pizza/American"}

이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.