Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go Driver
/ /

ドキュメントの置換

このガイドでは、 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() メソッドを使用して、このドキュメントを、値が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
}

注意

セットアップ例

この例では、接続 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 ドキュメントを参照してください。

戻る

Update Documents

項目一覧