개요
이 가이드에서는 업데이트 작업을 사용하여 MongoDB에서 문서를 업데이트하는 방법을 학습할 수 있습니다.
업데이트 작업은 다른 필드와 값을 변경하지 않고 유지하면서 지정한 필드를 변경합니다.
MongoDB에서 문서를 수정하는 모든 메서드는 동일한 패턴을 따릅니다.

참고
자리 표시자
changeX
(은)는 실제 메서드가 아닌 자리 표시자입니다.
이 패턴은 다음을 수행해야 합니다.
수정할 하나 이상의 문서와 일치하도록 쿼리 필터하다 를 지정합니다.
필드 및 값 변경 사항을 지정합니다.
메서드 동작을 수정해야 하는 경우 옵션을 지정합니다.
운전자 다음과 같은 방법으로 문서를 업데이트 수 있습니다.
UpdateByID()
:_id
을 기준으로 단일 문서 를 업데이트합니다.UpdateOne()
: 단일 문서 업데이트합니다.UpdateMany()
: 여러 문서를 업데이트합니다.
_id 에 대한 참고 사항
MongoDB 컬렉션 의 각 문서 에는 고유하고 변경할 수 없는 _id
필드 있습니다. 업데이트 작업을 사용하여 _id
필드 변경할 수 없습니다. 이 필드 변경하려고 하면 업데이트 메서드에서 WriteError
를 반환합니다.
매개변수
각 메서드는 하나 이상의 업데이트 연산자 를 포함하는 업데이트 문서 를 사용합니다. 업데이트 연산자는 수행할 업데이트 유형을 지정합니다. 업데이트 문서에는 변경 사항을 설명하는 필드와 값도 포함되어 있습니다. 업데이트 문서는 다음과 같은 포맷을 사용합니다.
bson.D{{"<update operator>", bson.D{{"<field>", <value>}, {"<field>", <value>}, ... }}, {"<update operator>", ... }, ... }
업데이트 연산자 및 설명의 전체 목록은 MongoDB 서버 매뉴얼을 참조하세요.
팁
UpdateOne()
제공한 쿼리 필터하다 와 일치하는 첫 번째 문서 업데이트합니다. 올바른 문서 업데이트 하려면 sort
옵션을 사용하여 작업에서 문서를 찾는 순서를 지정할 수 있습니다. 자세한 학습 은 UpdateOneOptions API 설명서를 참조하세요.
참고
업데이트 작업의 집계 파이프라인
업데이트 작업에서 집계 단계의 하위 집합으로 구성된 집계 파이프라인을 사용할 수 있습니다. 집계 파이프라인에서 MongoDB 지원하는 집계 단계에 대해 자세히 학습 서버 매뉴얼에서 집계 파이프라인으로 업데이트 튜토리얼을 참조하세요.
Return Values
UpdateOne()
, UpdateByID()
및 UpdateMany()
작업이 성공한 경우 업데이트 작업에 대한 정보가 포함된 UpdateResult
유형을 반환합니다. UpdateResult
유형에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
---|---|
| 필터하다 와 일치하는 문서 수 |
| 작업으로 수정된 문서 수입니다. |
| 작업에 의해 업서트된 문서 수입니다. |
| 업서트된 문서의 |
여러 문서가 UpdateOne()
에 전달된 쿼리 필터와 일치하는 경우 메서드는 일치하는 첫 번째 문서를 선택하여 업데이트합니다. 쿼리 필터와 일치하는 문서가 없는 경우 업데이트 작업은 변경되지 않습니다.
쿼리 필터하다 와 일치하는 문서가 없는 경우 새 문서 삽입하는 방법을 학습 업서트 가이드 참조하세요.
UpdateOne() 예제
다음 예시 Atlas 샘플 데이터 세트의 sample_airbnb
데이터 세트에 있는 listingsAndReviews
컬렉션 사용합니다. 다음 문서 에어비앤비 숙소 목록을 설명합니다.
{ "_id": "10006546", "listing_url": "https://www.airbnb.com/rooms/10006546", "name": "Ribeira Charming Duplex", "summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...", ... "minimum_nights": "2", "maximum_nights": "30", ... "accommodates": 8, ... }
다음 예시 에서는 UpdateOne()
메서드를 사용하여 다음을 수행합니다.
_id
값이"10006546"
인 문서를 일치시킵니다.name
필드"Ribiera River View Duplex"
(으)로 설정합니다.accommodates
필드의 값을1
만큼 증가시킵니다.
filter := bson.D{{"_id", "10006546"}} update := bson.D{{"$set", bson.D{{"name", "Ribiera River View Duplex"}}}, {"$inc", bson.D{{"accomodates", 1}}}} result, err := collection.UpdateOne(context.TODO(), filter, update) fmt.Printf("Documents matched: %v\n", result.MatchedCount) fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
Documents matched: 1 Documents updated: 1
다음은 이전 업데이트 작업의 결과로 업데이트된 문서를 보여줍니다.
{ "_id": "10006546", "listing_url": "https://www.airbnb.com/rooms/10006546", "name": "Ribeira River View Duplex", "summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...", ... "minimum_nights": "2", "maximum_nights": "30", ... "accommodates": 9, ... }
UpdateOne() 예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants
데이터베이스의 restaurants
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
다음 예시 restaurants
컬렉션 에 대해 다음 조치를 수행하는 완전히 실행 가능한 파일 입니다.
특정 항목이 있는 문서 찾습니다.
_id
일치하는 문서 의
avg_rating
필드 값을 업데이트합니다.
// Updates the first document that matches a query filter by using the Go driver package 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" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` AverageRating float64 `bson:"avg_rating,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") id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f4292b") filter := bson.D{{"_id", id}} // Creates instructions to add the "avg_rating" field to documents update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}} // Updates the first document that has the specified "_id" value result, err := coll.UpdateOne(context.TODO(), filter, update) if err != nil { panic(err) } // Prints the number of updated documents fmt.Printf("Documents updated: %v\n", result.ModifiedCount) // When you run this file for the first time, it should print output similar to the following: // Documents updated: 1 }
Documents updated: 1
UpdateMany() 예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants
데이터베이스의 restaurants
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
다음 예시 restaurants
컬렉션 에 대해 다음 조치를 수행하는 완전히 실행 가능한 파일 입니다.
cuisine
필드 값이"Pizza"
이고borough
필드 값이"Brooklyn"
인 문서를 찾습니다.일치하는 문서의
avg_rating
필드 값을 업데이트합니다.
// Updates documents that match a query filter by using the Go driver package 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" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` Cuisine string `bson:"cuisine"` AverageRating float64 `bson:"avg_rating,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{{"cuisine", "Pizza"}, {"borough", "Brooklyn"}} // Creates instructions to update the values of the "avg_rating" field update := bson.D{{"$set", bson.D{{"avg_rating", 4.5}}}} // Updates documents in which the value of the "Cuisine" // field is "Pizza" result, err := coll.UpdateMany(context.TODO(), filter, update) if err != nil { panic(err) } // Prints the number of updated documents fmt.Printf("Documents updated: %v\n", result.ModifiedCount) // end updatemany // When you run this file for the first time, it should print output similar to the following: // Documents updated: 296 }
Documents updated: 296
추가 정보
언급된 작업에 대해 자세히 알아보려면 다음 가이드를 참조하세요.
배열 요소 업데이트에 대해 자세히 알아보려면 문서의 배열 업데이트를 참조하세요.
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.