Docs Menu
Docs Home
/ / /
C++ ドライバー
/

データの変更を監視

項目一覧

  • Overview
  • サンプル データ
  • 変更ストリームを開く
  • 変更ストリーム出力の変更
  • watch()の動作を変更
  • 変更前と変更後のイメージを含めます
  • 詳細情報
  • API ドキュメント

このガイドでは、変更ストリームを使用してデータベースへのリアルタイムの変更を監視する方法を学習できます。 変更ストリームは、アプリケーションがコレクション、データベース、または配置のデータ変更をサブスクライブできる MongoDB Server の機能です。

C++ドライバーを使用すると、 mongocxx::change_streamをインスタンス化してデータの変更を監視できます。

このガイドの例では、 Atlasサンプルデータセットsample_restaurantsデータベースのrestaurantsコレクションを使用します。 C++アプリケーションからこのコレクションにアクセスするには、Atlasmongocxx::client クラスターに接続する をインスタンス化し、 変数と 変数に次の値を割り当てます。dbcollection

auto db = client["sample_restaurants"];
auto collection = db["restaurants"];

MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。

変更ストリームを開くには、 watch()メソッドを呼び出します。 watch()メソッドを呼び出す インスタンスによって、変更ストリームがリッスンするイベントの範囲が決まります。 次のクラスでwatch()メソッドを呼び出すことができます。

  • mongocxx::client: MongoDBデプロイのすべての変更を監視

  • mongocxx::database:データベース内のすべてのコレクションの変更を監視

  • mongocxx::collection:コレクションの変更を監視

次の例では、 restaurantsコレクションの変更ストリームを開き、変更が発生に応じて出力します。

auto stream = collection.watch();
while (true) {
for (const auto& event : stream) {
std::cout << bsoncxx::to_json(event) << std::endl;
}
}

変更の監視を開始するには、上記のコードを実行します。 次に、別のアプリケーションまたはshellで、restaurantsコレクションを変更します。 次の例では、 nameフィールドの値がBlarney Castleであるドキュメントを更新します。

auto result = collection.update_one(make_document(kvp("name", "Blarney Castle")),
make_document(kvp("$set",
make_document(kvp("cuisine", "Irish")))));

コレクションを更新すると、変更ストリームアプリケーションは変更が発生に応じて出力します。 出力される変更イベントは、次の出力のようになります。

{ "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" :
{ "$timestamp" : { ... }, "wallTime" : { "$date" : ... }, "ns" :
{ "db" : "sample_restaurants", "coll" : "restaurants" }, "documentKey" :
{ "_id" : { "$oid" : "..." } }, "updateDescription" : { "updatedFields" :
{ "cuisine" : "Irish" }, "removedFields" : [ ], "truncatedArrays" : [ ] } }

変更ストリーム出力を変更するには、 mongocxx::pipelineインスタンスをwatch()メソッドの引数として渡します。 次のリストには、対応する setter メソッドを呼び出して設定できる一部のmongocxx::pipelineフィールドが含まれています。

  • add_fields: ドキュメントに新しいフィールドを追加します

  • match: ドキュメントをフィルタリングします

  • project:ドキュメントフィールドのサブセットをプロジェクションします

  • redact: ドキュメントのコンテンツを制限します

  • group: 指定した式でドキュメントをグループ化します

  • merge: 結果をコレクションに出力します

Tip

mongocxx::pipelineフィールドの完全なリストについては、 mongocx::パイプライン を参照してください APIドキュメント。

次の例では、 mongocxx::pipelineインスタンスのmatchフィールドを設定し、パイプラインをwatch()メソッドに渡します。 これはwatch()メソッドに更新操作のみを出力するように指示します。

mongocxx::pipeline pipeline;
pipeline.match(make_document(kvp("operationType", "update")));
auto stream = collection.watch(pipeline);
while (true) {
for (const auto& event : stream) {
std::cout << bsoncxx::to_json(event) << std::endl;
}
}

mongocxx::options::change_streamクラスのインスタンスをパラメーターとして渡すことで、 watch()メソッドの動作を変更できます。 次の表では、 mongocxx::options::findインスタンスで設定できるフィールドを説明しています。

フィールド
説明
full_document
Specifies whether to show the full document after the change, rather than showing only the changes made to the document. To learn more about this option, see Include Pre-Images and Post-Images.
full_document_before_change
Specifies whether to show the full document as it was before the change, rather than showing only the changes made to the document. To learn more about this option, see Include Pre-Images and Post-Images.
resume_after
Instructs watch() to resume returning changes after the operation specified in the resume token.
Each change stream event document includes a resume token as the _id field. Pass the entire _id field of the change event document that represents the operation you want to resume after.
resume_after is mutually exclusive with start_after and start_at_operation_time.
start_after
Instructs watch() to start a new change stream after the operation specified in the resume token. This field allows notifications to resume after an invalidate event.
Each change stream event document includes a resume token as the _id field. Pass the entire _id field of the change event document that represents the operation you want to resume after.
start_after is mutually exclusive with resume_after and start_at_operation_time.
start_at_operation_time
Instructs watch() to return only events that occur after the specified timestamp.
start_at_operation_time is mutually exclusive with resume_after and start_after.
max_await_time_ms
Sets the maximum amount of time, in milliseconds, the server waits for new data changes to report to the change stream cursor before returning an empty batch. Defaults to 1000 milliseconds.
batch_size
Sets the maximum number of change events to return in each batch of the response from the MongoDB cluster.
collation
Sets the collation to use for the change stream cursor.
comment
Attaches a comment to the operation.

重要

配置で MongoDB v 6.0以降が使用されている場合にのみ、コレクションで変更前と変更後のイメージを有効にできます。

デフォルトでは 、コレクションに対して操作を実行すると、対応する変更イベントには、その操作によって変更されたフィールドのデルタのみが含まれます。 変更前または変更後の完全なドキュメントを表示するには、 インスタンスの フィールドまたはfull_document_before_change full_documentmongocxx::options::change_streamフィールドを指定します。

変更前のイメージは、変更のドキュメントの完全なバージョンです。 変更ストリームイベントに変更前のイメージを含めるには、 full_document_before_changeフィールドを次のいずれかの文字列に設定します。

  • "whenAvailable": 変更イベントには、変更前のイメージが利用可能な場合にのみ、 変更イベント 用の変更されたドキュメントの変更前のイメージが含まれます。

  • "required": 変更イベントには、変更イベント用に変更されたドキュメントの変更前のイメージが含まれます。 変更前のイメージが利用できない場合、ドライバーはエラーを発生させます。

変更後のイメージとは、変更のドキュメントの完全なバージョンです。 変更ストリームイベントに変更後のイメージを含めるには、 full_documentフィールドを次のいずれかの文字列に設定します。

  • "updateLookup": 変更イベントには、変更後一定時間の変更されたドキュメント全体のコピーが含まれます。

  • "whenAvailable": 変更イベントには、変更後のイメージが利用可能な場合にのみ、 変更イベント 用の変更されたドキュメントの変更後のイメージが含まれます。

  • "required": 変更イベントには、変更イベントの変更されたドキュメントの変更後のイメージが含まれます。 変更後のイメージが利用できない場合、ドライバーはエラーを発生させます。

次の例では、コレクションでwatch()メソッドを呼び出し、 mongocxx::options::change_streamインスタンスのfull_documentフィールドを設定して更新されたドキュメントの変更後のイメージを含めます。

mongocxx::options::change_stream opts;
opts.full_document("updateLookup");
auto stream = collection.watch(opts);
while (true) {
for (const auto& event : stream) {
std::cout << bsoncxx::to_json(event) << std::endl;
}
}

を実行中している変更ストリームアプリケーションで、前述の更新例を使用してrestaurantsコレクション内のドキュメントを更新すると、次のコードのような変更イベントが出力されます。

{ "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" :
{ "$timestamp" : { ... } }, "wallTime" : { "$date" : ... },
"fullDocument" : { "_id" : { "$oid" : "..." }, "address" : { "building" : "202-24",
"coord" : [ -73.925044200000002093, 40.559546199999999772 ], "street" :
"Rockaway Point Boulevard", "zipcode" : "11697" }, "borough" : "Queens", "cuisine" :
"Irish", "grades" : [ ... ], "name" : "Blarney Castle", "restaurant_id" : "40366356" },
"ns" : { "db" : "sample_restaurants", "coll" : "restaurants" }, "documentKey" :
{ "_id" : { "$oid" : "..." } }, "updateDescription" : { "updatedFields" :
{ "cuisine" : "Irish" }, "removedFields" : [ ], "truncatedArrays" : [ ] } }

Tip

変更前と変更後のイメージの詳細については、Change Streams MongoDB Serverマニュアルの「 とドキュメントの変更 前イメージおよび変更後イメージ 」を参照してください。

Change Streams変更ストリームの詳細については、MongoDB Server マニュアルの 「 ストリーム」 を参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

カーソルからデータにアクセスする