Replace a Document — Go
Docs Menu

Docs HomeGo

ドキュメントの置き換え

コレクション内のドキュメントを置き換えるには、 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.

ReplaceOne()

フィードバックを送る