ドキュメントの置き換え
コレクション内のドキュメントを置き換えるには、 ReplaceOne()
メソッドを使用します。
例
Tip
この例を実行する方法については、「使用例」をお読みください。
次の例では、haikus
コレクションに対して次の操作を実行します。
Matches a document in which the
title
is "Record of a Shriveled Datum"一致したドキュメントを新しいドキュメントに置き換えます
coll := client.Database("insertDB").Collection("haikus") filter := bson.D{{"title", "Record of a Shriveled Datum"}} replacement := bson.D{{"title", "Dodging Greys"}, {"text", "When there're no matches, no longer need to panic. You can use upsert"}} result, err := coll.ReplaceOne(context.TODO(), filter, replacement) if err != nil { panic(err) }
期待される結果
完全な例を実行すると、 haikus
コレクションに次の置換されたドキュメントが見つかります。
{ "_id" : ObjectId("..."), "title" : "Dodging Greys", "text" : "When there're no matches, no longer need to panic. You can use upsert." }
ドキュメントの検索方法の例については、「ドキュメントを検索する
詳細情報
To learn more about replacing documents, specifying query filters, and handling potential errors, see Change a Document.