Docs Menu
Docs Home
/ /

Tutorial

このチュートリアルの完全なコードは tuned.cpp でご覧ください。

  • ポート27017の localhost で実行中のmongodインスタンス。

  • mongocx ドライバー。 「 のインストール 」を参照してください。

  • ソース ファイルの上部にある次のステートメント。

#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_array;
using bsoncxx::builder::basic::make_document;

mongocx ドライバーのインストール プロセスでは、pkg-config で使用するための libmongocxx.pcファイルがインストールされます。

プログラムをコンパイルするには、次のコマンドを実行します。

c++ --std=c++11 <input>.cpp $(pkg-config --cflags --libs libmongocxx)

pkg-config が使用できない場合は、コマンドラインまたは IDE で 含める フラグと ライブラリ フラグを手動で設定する必要があります。 たとえば、 libmongoc と mongocx が/usr/localにインストールされている場合、上記の のコンパイル行は次のように展開されます。

c++ --std=c++11 <input>.cpp
-I/usr/local/include/mongocxx/v_noabi \
-I/usr/local/include/bsoncxx/v_noabi \
-L/usr/local/lib -lmongocxx -lbsoncxx

重要

接続を行う前に、mongocxx::インスタンスの 1 つのインスタンスのみを作成する必要があります。このインスタンスは、プログラム全体に存在する必要があります。

実行中のMongoDBインスタンスに接続するには、 mongocx::インスタンスクラスを使用します。

MongoDB URI を含む mongocx::uriインスタンスを使用して接続するホストを指定し、それをmongocxx::client コンストラクターに渡す必要があります。サポートされている URI オプションの詳細については、 C++ドライバーの構築に使用される libmongoc のバージョンまたは最新の libmongoc リリースのドキュメントを参照してください。

デフォルトのmongocxx::uriコンストラクターは、ポート27017の localhost で実行されているサーバーに接続します。

mongocxx::instance instance{}; // This should be done only once.
mongocxx::client client{mongocxx::uri{}};

これは、次の と同等です。

mongocxx::instance instance{}; // This should be done only once.
mongocxx::uri uri("mongodb://localhost:27017");
mongocxx::client client(uri);

mongocx::インスタンスがMongoDBデプロイに接続されたら、database() メソッドまたはoperator[] を使用して mongocx::データベースインスタンスを取得します。

リクエストするデータベースが存在しない場合は、データを最初に保存するときに MongoDB によってデータベースが作成されます。

次の例では、 mydbデータベースにアクセスします。

auto db = client["mydb"];

mongocxx::データベースインスタンスが作成したら、collection() メソッドまたは operator[] を使用してmongocxx::コレクションインスタンスを取得します。

リクエストしたコレクションが存在しない場合、MongoDB は最初にデータを保存するときにコレクションを作成します。

たとえば、次のステートメントは、前のセクションで作成されたdbインスタンスを使用して、 mydbデータベース内のtestという名前のコレクションにアクセスします。

auto collection = db["test"];

C++ ドライバーを使用してdocumentを作成するには、使用可能な 2 つのビルダ インターフェイスのいずれかを使用します。

  • ストリーム ビルダ: bsoncxx::builder::stream
    リテラル ドキュメント構築に適した ストリーミング演算子 を使用するドキュメント ビルダー。
  • 基本ビルダ: bsoncxx::builder::basic
    ビルダ インスタンスでメソッドを呼び出す、より従来のドキュメント ビルダ。

このガイドでは、基本ビルダについて簡単に説明します。

たとえば、次の JSON ドキュメントについて考えてみます。

{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"versions": [ "v6.0", "v5.0", "v4.4", "v4.2", "v4.0", "v3.6" ],
"info" : {
"x" : 203,
"y" : 102
}
}

基本的なビルダを使用すると、次のようにこのドキュメントを構築できます。

auto doc_value = make_document(
kvp("name", "MongoDB"),
kvp("type", "database"),
kvp("count", 1),
kvp("versions", make_array("v6.0", "v5.0", "v4.4", "v4.2", "v4.0", "v3.6")),
kvp("info", make_document(kvp("x", 203), kvp("y", 102)))
);

この bsoncxx::document::value 型は、独自のメモリを所有する読み取り専用オブジェクトです。これを使用するには、 メソッドを使用して bsoncx::ドキュメント: ビューを取得する必要があります。view()

auto doc_view = doc_value.view();

を使用してこのドキュメントビュー内のフィールドにアクセスできます。これによりoperator[] bsoncx::ドキュメント:: 要素インスタンスが返されます。例、次の例では、値が string である nameフィールドが抽出されます。

auto element = doc_view["name"];
assert(element.type() == bsoncxx::type::k_string);
auto name = element.get_string().value; // For C++ driver version < 3.7.0, use get_utf8()
assert(0 == name.compare("MongoDB"));

名前フィールドの値が string ではなく、前述の例に示すように型保護を含めない場合、このコードは bsoncxx::例外 のインスタンスをスローします。

コレクション に単一のドキュメントを挿入するには、mongocx::コレクションインスタンスの insert_one() メソッドを使用して { "i": 0 } を挿入します。

auto insert_one_result = collection.insert_one(make_document(kvp("i", 0)));

insert_one_result は、任意の mongocxx::result::insert_one です。この例では 、insert_one_result が設定されることが予想されています。書込み (write) 操作のデフォルトの動作は、サーバーからの応答を待つことです。これは、確認されていない mongocxx::write_concern. を設定することで上書きされる可能性があります。

assert(insert_one_result); // Acknowledged writes return results.

ドキュメントに最上位の_idフィールドを指定しない場合、MongoDB は挿入されたドキュメントに_idフィールドを自動的に追加します。

この値は、返された mongocxx::result::insert_one インスタンスの inserted_id() メソッドを使用して取得できます。

auto doc_id = insert_one_result->inserted_id();
assert(doc_id.type() == bsoncxx::type::k_oid);

コレクションに複数のドキュメントを挿入するには、 mongocxx::コレクション インスタンスの insert_many() メソッドを使用します。このメソッドは挿入するドキュメントのリストを受け取ります。

次の例では、ドキュメント{ "i": 1 }{ "i": 2 }を挿入しています。 ドキュメントを作成し、ドキュメント リストに追加します。

std::vector<bsoncxx::document::value> documents;
documents.push_back(make_document(kvp("i", 1)));
documents.push_back(make_document(kvp("i", 2)));

これらのドキュメントをコレクションに挿入するには、ドキュメントのリストをinsert_many()メソッドに渡します。

auto insert_many_result = collection.insert_many(documents);
assert(insert_many_result); // Acknowledged writes return results.

各ドキュメントで最上位の_idフィールドを指定しない場合、MongoDB は挿入されたドキュメントに自動的に_idフィールドを追加します。

この値は、返された mongocxx::result::insert_many インスタンスの inserted_ids() メソッドを使用して取得できます。

auto doc0_id = insert_many_result->inserted_ids().at(0);
auto doc1_id = insert_many_result->inserted_ids().at(1);
assert(doc0_id.type() == bsoncxx::type::k_oid);
assert(doc1_id.type() == bsoncxx::type::k_oid);

コレクションをクエリするには、コレクションのfind() メソッドとfind_one() メソッドを使用します。

find() mongocx::cursor のインスタンスを返し、 はfind_one() std::optional< bsoncxx::document::value >のインスタンスを返します。詳細については、bsoncxx::ドキュメント::value を参照してください。

空のドキュメントを指定して コレクション内のすべてのドキュメントをクエリするか、フィルターを渡してフィルター条件に一致するドキュメントをクエリできます。

コレクション内の単一のドキュメントを返すには、パラメータなしでfind_one()メソッドを使用します。

auto find_one_result = collection.find_one({});
if (find_one_result) {
// Do something with *find_one_result
}
assert(find_one_result);
auto cursor_all = collection.find({});
for (auto doc : cursor_all) {
// Do something with doc
assert(doc["_id"].type() == bsoncxx::type::k_oid);
}

bsoncxx::to_json 関数は、BSONドキュメントをJSON string に変換します。

auto cursor_all = collection.find({});
std::cout << "collection " << collection.name()
<< " contains these documents:" << std::endl;
for (auto doc : cursor_all) {
std::cout << bsoncxx::to_json(doc, bsoncxx::ExtendedJsonMode::k_relaxed) << std::endl;
}
std::cout << std::endl;

上記の例では、次のような出力が印刷されます。

collection test contains these documents:
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a1" }, "i" : 0 }
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a2" }, "i" : 1 }
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a3" }, "i" : 2 }

_id要素は MongoDB によってドキュメントに自動的に追加され、値は表示されている値とは異なります。 MongoDB では、内部使用のためにアンダースコア( _ )とドル記号( $ )で始まるフィールド名が予約されます。

フィールドiの値が0である最初のドキュメントを検索するには、ドキュメント{"i": 0}を渡して等価条件を指定します。

auto find_one_filtered_result = collection.find_one(make_document(kvp("i", 0)));
if (find_one_filtered_result) {
// Do something with *find_one_filtered_result
}

次の例では、 0 < "i" <= 2であるすべてのドキュメントを取得しています。

auto cursor_filtered =
collection.find(make_document(kvp("i", make_document(kvp("$gt", 0), kvp("$lte", 2)))));
for (auto doc : cursor_filtered) {
// Do something with doc
assert(doc["_id"].type() == bsoncxx::type::k_oid);
}

コレクション内のドキュメントを更新するには、コレクションのupdate_one() メソッドとupdate_many() メソッドを使用できます。

更新メソッドは std::optional< mongocxx::result::update > のインスタンスを返します。このインスタンスは、更新によって変更されたドキュメント数などの操作に関する情報を提供します。詳しくは、mongocxx::result::update を参照してください。

最大で 1 つのドキュメントを更新するには、 update_one()メソッドを使用します。

次の例では、フィルター{ "i": 0 }に一致する最初のドキュメントを更新し、 fooの値をbarに設定します。

auto update_one_result =
collection.update_one(make_document(kvp("i", 0)),
make_document(kvp("$set", make_document(kvp("foo", "bar")))));
assert(update_one_result); // Acknowledged writes return results.
assert(update_one_result->modified_count() == 1);

フィルターに一致するすべてのドキュメントを更新するには、 update_many()メソッドを使用します。

次の例では、 i0より大きい場合、 fooの値をbuzzに設定します。

auto update_many_result =
collection.update_many(make_document(kvp("i", make_document(kvp("$gt", 0)))),
make_document(kvp("$set", make_document(kvp("foo", "buzz")))));
assert(update_many_result); // Acknowledged writes return results.
assert(update_many_result->modified_count() == 2);

コレクションからドキュメントを削除するには、コレクションのdelete_one() メソッドとdelete_many() メソッドを使用できます。

削除 メソッドは、削除されたドキュメントの数を含む std::optional< mongocxx::result::delete > のインスタンスを返します。詳しくは、mongocxx::result::delete を参照してください。

フィルターに一致するドキュメントを最大で 1 つ削除するには、 delete_one()メソッドを使用します。

たとえば、フィルター{ "i": 0 }に一致するドキュメントを削除するには、次の操作を実行します。

auto delete_one_result = collection.delete_one(make_document(kvp("i", 0)));
assert(delete_one_result); // Acknowledged writes return results.
assert(delete_one_result->deleted_count() == 1);

フィルターに一致するすべてのドキュメントを削除するには、コレクションのdelete_many()メソッドを使用します。

次の例では、 i0より大きいすべてのドキュメントを削除しています。

auto delete_many_result =
collection.delete_many(make_document(kvp("i", make_document(kvp("$gt", 0)))));
assert(delete_many_result); // Acknowledged writes return results.
assert(delete_many_result->deleted_count() == 2);

create_index()フィールドまたはフィールドのセットにインデックスを作成するには、インデックス仕様ドキュメントをmongocx::コレクションインスタンスの メソッドに渡します。インデックスキー仕様ドキュメントには、インデックスを作成するフィールドと各フィールドのインデックスタイプが含まれています。

{ "index1": "<type>", "index2": "<type>" }
  • 昇順のインデックス タイプの場合は、 <type>の1を指定します。

  • 降順のインデックス タイプでは、 <type>の - 1を指定します。

次の例では、 iフィールドに昇順のインデックスを作成しています。

auto index_specification = make_document(kvp("i", 1));
collection.create_index(std::move(index_specification));

戻る

クライアント側の暗号化