Overview
このガイドでは、 Goドライバーを使用してMongoDBコレクション内のドキュメントに対して置換操作を実行する方法を学習できます。置換操作は更新操作とは異なります。アップデート操作、ターゲットドキュメント内の指定されたフィールドのみが変更されます。置換操作、ターゲットドキュメント内のすべてのフィールドが削除され、新しいフィールドに置き換えられます。
パラメーター
ReplaceOne()
は、既存のドキュメントの代わりに使用するドキュメントである置換ドキュメントを要求しています。 置換ドキュメントは以下の形式を使用します。
bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... }
Return Values
ReplaceOne()
は、置換操作が成功した場合、置換操作に関する情報を含むUpdateResult
型を返します。 UpdateResult
型には次のプロパティが含まれています。
プロパティ | 説明 |
---|---|
| フィルターに一致するドキュメントの数 |
| 操作によって変更されたドキュメントの数 |
| 操作によってアップサートされたドキュメントの数 |
| アップサートされたドキュメントの |
ReplaceOne()
に渡されたクエリフィルターに一致するドキュメントが複数ある場合、メソッドは最初に一致したドキュメントを選択して置き換えます。 クエリフィルターに一致するドキュメントがない場合、置換操作は失敗します。
例
次のドキュメントでは、テーブル アイテムを説明しています。
{ "_id" : 2056, "item" : "Mug", "brand" : "Simply Ceramics", "price" : 2.99, "material" : "Glass" }
次の例では、ReplaceOne()
メソッドを使用して、このドキュメントを、値がitem
"Cup" のquantity
フィールドと値が の107 フィールドを含むドキュメントに置き換えます。
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)
Documents matched: 1 Documents replaced: 1
置換されたドキュメントには、次のように、置換ドキュメントの内容と不変の_id
フィールドが含まれます。
{ "_id" : 2056, "item" : "Cup", "quantity" : 107 }
1 つのドキュメントの置き換えの例: 完全なファイル
注意
セットアップ例
この例では、接続 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 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" ) 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"` } 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/ja-jp/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 }
Number of documents replaced: 1
期待される結果
完全な例を実行すると、 restaurants
コレクションに次の置換されたドキュメントが見つかります。
{ "_id" : ObjectId("..."), "name" : "Rizzo's Pizza", "cuisine" : "Pizza/American" }
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。