AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

変更ストリームを開く例

Watch()メソッドを使用して、 Collection 、 Database 、またはClientで変更ストリームを開くことができます。

Tip

この例を実行する方法については、「使用例」をお読みください。

次の例では、 restaurantsコレクションの変更ストリームを開き、挿入されたドキュメントを出力します。

coll := client.Database("sample_restaurants").Collection("restaurants") // Creates instructions to watch for insert operationspipeline := mongo.Pipeline{bson.D{{"$match", bson.D{{"operationType", "insert"}}}}} // Creates a change stream that receives change eventscs, err := coll.Watch(context.TODO(), pipeline)if err != nil { panic(err)}defer cs.Close(context.TODO()) fmt.Println("Waiting For Change Events. Insert something in MongoDB!") // Prints a message each time the change stream receives an eventfor cs.Next(context.TODO()) { var event bson.M if err := cs.Decode(&event); err != nil { panic(err) } output, err := json.MarshalIndent(event["fullDocument"], "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output)}if err := cs.Err(); err != nil { panic(err)}

完全に実行可能な例を表示します。

完全な例を実行したら、別の shell でドキュメントの挿入 の使用例を実行します。 挿入操作を実行すると、次の出力が表示されます。

// results truncated{ "_id": ..., "name": "8282", "cuisine": "Korean"}

重要

終了したら、ターミナルを閉じてこの使用例をシャットダウンしてください。

変更ストリームを開き、潜在的なエラーを処理するの詳細については、以下を参照してください。

Watch()

このページを評価