See the full code for this tutorial in tutorial.cpp.
前提条件
ポート27017の localhost で実行中のmongodインスタンス。
mongocx ドライバー。 「 のインストール 」を参照してください。
ソース ファイルの上部にある次のステートメント。
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_array; using bsoncxx::builder::basic::make_document;
コンパイル
The mongocxx driver's installation process will install a libmongocxx.pc
file for use with pkg-config.
プログラムをコンパイルするには、次のコマンドを実行します。
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
接続を行う
重要
Before making any connections, you need to create one and only one instance of mongocxx::instance. This instance must exist for the entirety of your program.
To connect to a running MongoDB instance, use the mongocxx::instance class.
You must specify the host to connect to using a mongocxx::uri instance containing a MongoDB URI, and pass that into the mongocxx::client
constructor. For details regarding supported URI options see the documentation for the version of libmongoc used to build the C++ driver or for the latest libmongoc release.
デフォルトの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);
データベースへのアクセス
Once you have a mongocxx::instance instance connected to a MongoDB deployment, use either the database()
method or operator[]
to obtain a mongocxx::database instance.
リクエストするデータベースが存在しない場合は、データを最初に保存するときに MongoDB によってデータベースが作成されます。
次の例では、 mydb
データベースにアクセスします。
auto db = client["mydb"];
コレクションにアクセスする
Once you have a mongocxx::database instance, use either the collection()
method or operator[]
to obtain a mongocxx::collection instance.
リクエストしたコレクションが存在しない場合、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))) );
This bsoncxx::document::value
type is a read-only object owning its own memory. To use it, you must obtain a bsoncxx::document::view using the view()
method:
auto doc_view = doc_value.view();
You can access fields within this document view using operator[]
, which will return a bsoncxx::document::element instance. For example, the following will extract the name
field whose value is a string:
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"));
If the value in the name field is not a string and you do not include a type guard as seen in the preceding example, this code will throw an instance of bsoncxx::exception.
ドキュメントの挿入
1つのドキュメントの挿入
To insert a single document into the collection, use a mongocxx::collection instance's insert_one()
method to insert { "i": 0 }
:
auto insert_one_result = collection.insert_one(make_document(kvp("i", 0)));
insert_one_result
is an optional mongocxx::result::insert_one. In this example, insert_one_result
is expected to be set. The default behavior for write operations is to wait for a reply from the server. This may be overridden by setting an unacknowledged mongocxx::write_concern.
assert(insert_one_result); // Acknowledged writes return results.
ドキュメントに最上位の_id
フィールドを指定しない場合、MongoDB は挿入されたドキュメントに_id
フィールドを自動的に追加します。
You can obtain this value using the inserted_id()
method of the returned mongocxx::result::insert_one instance.
auto doc_id = insert_one_result->inserted_id(); assert(doc_id.type() == bsoncxx::type::k_oid);
複数のドキュメントの挿入
To insert multiple documents to the collection, use a mongocxx::collection instance's insert_many()
method, which takes a list of documents to insert.
次の例では、ドキュメント{ "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
フィールドを追加します。
You can obtain this value using the inserted_ids()
method of the returned mongocxx::result::insert_many instance.
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()
will return an instance of mongocxx::cursor, while find_one()
will return an instance of std::optional< bsoncxx::document::value >
. For more information, see bsoncxx::document::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); }
コレクション内のすべてのドキュメントの出力
The bsoncxx::to_json function converts a BSON document to a 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 Documents
コレクション内のドキュメントを更新するには、コレクションのupdate_one()
メソッドとupdate_many()
メソッドを使用できます。
The update methods return an instance of std::optional<
mongocxx::result::update >
, which provides information about the operation including the number of documents modified by the update. For more information, see 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()
メソッドを使用します。
次の例では、 i
が0
より大きい場合、 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 Documents
コレクションからドキュメントを削除するには、コレクションのdelete_one()
メソッドとdelete_many()
メソッドを使用できます。
The delete methods return an instance of std::optional<
mongocxx::result::delete >
, which contains the number of documents deleted. For more information, see 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()
メソッドを使用します。
次の例では、 i
が0
より大きいすべてのドキュメントを削除しています。
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);
インデックスの作成
To create an index on a field or set of fields, pass an index specification document to the create_index()
method of a mongocxx::collection instance. An index key specification document contains the fields to index and the index type for each field:
{ "index1": "<type>", "index2": "<type>" }
昇順のインデックス タイプの場合は、
<type>
の1を指定します。降順のインデックス タイプでは、
<type>
の - 1を指定します。
次の例では、 i
フィールドに昇順のインデックスを作成しています。
auto index_specification = make_document(kvp("i", 1)); collection.create_index(std::move(index_specification));