Docs Menu
Docs Home
/ /

Tutorial

このガイドでは、MongoDB C ドライバーについて簡単に紹介します。

C APIの詳細については、 APIを参照してください。

MongoDB C ドライバーを特定のプラットフォームにインストールする方法の詳細については、 インストール ガイドをご覧ください。

このチュートリアルの例を実行するには、MongoDB がデフォルト ポートの27017 localhostにインストールされ、実行されている必要があります。 起動して実行中であるかどうかを確認するには、MongoDB shell を使用して に接続します。

$ mongosh --host localhost --port 27017 --quiet
Enterprise rs0 [direct: primary] test> db.version()
7.0.0
>

すべての libmongoc の関数と型は 1 つのヘッダーファイルで利用できます。 単純にmongoc/mongoc.hを含めます。

#include <mongoc/mongoc.h>

libmongoc のインストールには CMax 構成ファイルパッケージが含まれているため、C Search の find_ Package コマンドを使用して libmongoc の CSpec ターゲットと libmongoc (共有ライブラリとして)にリンクできます。

CSpecLists.txt
# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_shared)

代わりに、libmongoc を静的ライブラリとして使用することもできますmongo::mongoc_static CSpec ターゲットを使用します。

# Specify the minimum version you require.
find_package (mongoc-1.0 1.7 REQUIRED)
# The "hello_mongoc.c" sample program is shared among four tests.
add_executable (hello_mongoc ../../hello_mongoc.c)
target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_static)

Cake を使用していない場合は、コマンドラインで pkg-config を使用して ヘッダーとライブラリ パスを設定します。

gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)

または libmongoc に静的にリンクするには次のようにします。

gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)

C# または pkg-config を使用していない場合、パスとライブラリは手動で管理できます。

$ gcc -o hello_mongoc hello_mongoc.c \
-I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
-lmongoc-1.0 -lbson-1.0
$ ./hello_mongoc
{ "ok" : 1.000000 }

Windows ユーザーの場合、コードは次のコマンドでコンパイルして実行できます。 (MongoDB C ドライバーがC:\mongo-c-driverにインストールされていることを前提としています。必要に応じて include ディレクトリを変更します)。

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 hello_mongoc.c
C:\> hello_mongoc
{ "ok" : 1.000000 }

詳しくは、 libmongoc と Visual Studio のガイドを参照してください。

MongoDBには mongoc_client_t を使用してアクセスします。スタンドアロンサーバー、レプリカセット、シャーディングされたクラスターにオンデマンドで透過的に接続します。データベースまたはコレクションに対して操作を実行するには、 mongoc_client_t から mongoc_database_t または mongoc_collection_t 構造体を作成します。

アプリケーションの開始時に、他の libmongoc 関数の前に mongoc_init を呼び出します。最後に、各コレクション、データベース、またはクライアント処理に対して、それらが構築された方法と逆の順序で適切な破棄関数を呼び出します。終了する前に mongoc_クリーンアップ を呼び出します。

以下の例では、 localhost上のスタンドアロン サーバーへの接続を確立し、クライアント アプリケーションを「接続例」として登録して、簡単なコマンドを実行します。

データベース操作の詳細については、「 CRUD 操作実行コマンドの実行 」セクションを参照してください。 レプリカセットとシャーディングされたクラスターへの接続の例は [高度な接続] ページに、データ圧縮の例は [データ圧縮] ページを参照してください。

hello_mongoc.c
#include <mongoc/mongoc.h>
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://localhost:27017";
mongoc_uri_t *uri;
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;
bson_t *command, reply, *insert;
bson_error_t error;
char *str;
bool retval;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init ();
/*
* Optionally get MongoDB URI from command line
*/
if (argc > 1) {
uri_string = argv[1];
}
/*
* Safely create a MongoDB URI object from the given string
*/
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
/*
* Create a new client instance
*/
client = mongoc_client_new_from_uri (uri);
if (!client) {
return EXIT_FAILURE;
}
/*
* Register the application name so we can track it in the profile logs
* on the server. This can also be done from the URI (see other examples).
*/
mongoc_client_set_appname (client, "connect-example");
/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
database = mongoc_client_get_database (client, "db_name");
collection = mongoc_client_get_collection (client, "db_name", "coll_name");
/*
* Do work. This example pings the database, prints the result as JSON and
* performs an insert
*/
command = BCON_NEW ("ping", BCON_INT32 (1));
retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
if (!retval) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
str = bson_as_json (&reply, NULL);
printf ("%s\n", str);
insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (insert);
bson_destroy (&reply);
bson_destroy (command);
bson_free (str);
/*
* Release our handles and clean up libmongoc
*/
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}

ドキュメントは MongoDB のデータ形式、BSON で保存されます。 C ドライバーはlibbsonを使用して BSON ドキュメントを作成します。 これらを構築するには、キーと値のペアを追加する方法、BCON を使用する方法、JSON を解析する方法などがあります。

コード内で bson_t として表されるBSONドキュメント は、 libbson の Append 関数を使用して一度に 1 つのフィールドを構築できます。

たとえば、次のようなドキュメントを作成するには、次のようにします。

{
born : ISODate("1906-12-09"),
died : ISODate("1992-01-01"),
name : {
first : "Grace",
last : "Hopper"
},
languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
}

次のコードを使用します。

#include <bson/bson.h>
int
main (void)
{
struct tm born = {0};
struct tm died = {0};
const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
const char *schools[] = {"Vassar", "Yale"};
const char *degrees[] = {"BA", "PhD"};
uint32_t i;
bson_t *document;
bson_t child;
bson_array_builder_t *bab;
char *str;
document = bson_new ();
/*
* Append { "born" : ISODate("1906-12-09") } to the document.
* Passing -1 for the length argument tells libbson to calculate the
* string length.
*/
born.tm_year = 6; /* years are 1900-based */
born.tm_mon = 11; /* months are 0-based */
born.tm_mday = 9;
bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
/*
* Append { "died" : ISODate("1992-01-01") } to the document.
*/
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
/*
* For convenience, this macro passes length -1 by default.
*/
BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
/*
* Append a subdocument.
*/
BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
BSON_APPEND_UTF8 (&child, "first", "Grace");
BSON_APPEND_UTF8 (&child, "last", "Hopper");
bson_append_document_end (document, &child);
/*
* Append array of strings. Generate keys "0", "1", "2".
*/
BSON_APPEND_ARRAY_BUILDER_BEGIN (document, "languages", &bab);
for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
bson_array_builder_append_utf8 (bab, lang_names[i], -1);
}
bson_append_array_builder_end (document, bab);
/*
* Array of subdocuments:
* degrees: [ { degree: "BA", school: "Vassar" }, ... ]
*/
BSON_APPEND_ARRAY_BUILDER_BEGIN (document, "degrees", &bab);
for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
bson_array_builder_append_document_begin (bab, &child);
BSON_APPEND_UTF8 (&child, "degree", degrees[i]);
BSON_APPEND_UTF8 (&child, "school", schools[i]);
bson_array_builder_append_document_end (bab, &child);
}
bson_append_array_builder_end (document, bab);
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}

bson_t に追加できるすべてのタイプについては、 libbson のドキュメントを参照してください。

BSON C Object Notation (省略すると BSON )は、BSON ドキュメントをより目的の形式に近い方法で作成する代替方法です。 BSON の追加関数よりも型の安全性は低いが、コードは少なくなります。

#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
bson_t *document;
char *str;
born.tm_year = 6;
born.tm_mon = 11;
born.tm_mday = 9;
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
document = BCON_NEW (
"born", BCON_DATE_TIME (mktime (&born) * 1000),
"died", BCON_DATE_TIME (mktime (&died) * 1000),
"name", "{",
"first", BCON_UTF8 ("Grace"),
"last", BCON_UTF8 ("Hopper"),
"}",
"languages", "[",
BCON_UTF8 ("MATH-MATIC"),
BCON_UTF8 ("FLOW-MATIC"),
BCON_UTF8 ("COBOL"),
"]",
"degrees", "[",
"{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
"{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
"]");
/*
* Print the document as a JSON string.
*/
str = bson_as_canonical_extended_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}

BCON では配列、サブドキュメント、任意のフィールドを作成できることに注意してください。

単一ドキュメントの場合、 BSON はbson_new_from_json 経由でJSON string から作成できます。

#include <bson/bson.h>
int
main (int argc,
char *argv[])
{
bson_error_t error;
bson_t *bson;
char *string;
const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
if (!bson) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
string = bson_as_canonical_extended_json (bson, NULL);
printf ("%s\n", string);
bson_free (string);
return 0;
}

JSONドキュメントのシーケンスからBSON を初期化するには、bson_json_reader_t を使用します。

このセクションでは、C ドライバー を使用して MongoDB を操作する方法の基本を説明します。

コレクションにドキュメントを挿入するには、まず mongoc_client_t 経由で mongoc_collection_t への処理を取得します。次に、mongoc_collection_insert_one を使用して、BSONドキュメントをコレクションに追加します。この例では、データベース"mydb" とコレクション"mycoll" に挿入します。

終了したら、それぞれの破棄関数を使用して、割り当てられた構造が解放されていることを確認します。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./insert

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
C:\> insert

挿入が成功したことを確認するには、MongoDB shell に接続します。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find()
{ "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
>

Cドライバーを使用してMongoDBコレクションをクエリするには、関数 mongoc_collection_find_with_ops を使用します。これにより、一致するドキュメントへの カーソル が返されます。次の例では結果カーソルを反復処理し、stdout との一致をJSON string として出力します。

クエリ指定子としてドキュメントを使用します。たとえば、

{ "color" : "red" }

は、値が「red」である「core」という名前のフィールドを持つ任意のドキュメントと一致します。 空のドキュメント{}はすべてのドキュメントを一致させるために使用できます。

この最初の例では、空のクエリ指定子を使用して、データベース "mydb" とコレクション "mycoll" 内のすべてのドキュメントを検索します。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=find-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
C:\> find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

特定のドキュメントを検索するには、 queryに指定子を追加します。 この例では、 BSON_APPEND_UTF8()への呼び出しを追加して、 {"hello" : "world"}に一致するすべてのドキュメントを検索します。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client = mongoc_client_new (
"mongodb://localhost:27017/?appname=find-specific-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
BSON_APPEND_UTF8 (query, "hello", "world");
cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_canonical_extended_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
$ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
C:\> find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

このコード スニペットは、mongoc_collection_update_one を使用してドキュメントのフィールドを更新する例を示します。

次の例では、「mydb」データベースを使用して、「mycoll」コレクションにサンプル ドキュメントを挿入しています。 次に、 _idフィールドを使用して、ドキュメントは別の値と新しいフィールドで更新されます。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_collection_t *collection;
mongoc_client_t *client;
bson_error_t error;
bson_oid_t oid;
bson_t *doc = NULL;
bson_t *update = NULL;
bson_t *query = NULL;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=update-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
bson_oid_init (&oid, NULL);
doc = BCON_NEW ("_id", BCON_OID (&oid), "key", BCON_UTF8 ("old_value"));
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
query = BCON_NEW ("_id", BCON_OID (&oid));
update = BCON_NEW ("$set",
"{",
"key",
BCON_UTF8 ("new_value"),
"updated",
BCON_BOOL (true),
"}");
if (!mongoc_collection_update_one (
collection, query, update, NULL, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
fail:
if (doc)
bson_destroy (doc);
if (query)
bson_destroy (query);
if (update)
bson_destroy (update);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./update

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
C:\> update
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }

更新が成功したことを確認するには、MongoDB shell に接続します。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find({"updated" : true})
{ "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
>

この例では、 mongoc_collection_delete_one を使用してドキュメントを削除する方法を示しています。

次のコードは、サンプル ドキュメントを データベース "mydb" と コレクション "mycoll" に挿入します。 次に、 {"hello" : "world"}に一致するすべてのドキュメントが削除されます。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=delete-example");
collection = mongoc_client_get_collection (client, "test", "test");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
fprintf (stderr, "Insert failed: %s\n", error.message);
}
bson_destroy (doc);
doc = bson_new ();
BSON_APPEND_OID (doc, "_id", &oid);
if (!mongoc_collection_delete_one (
collection, doc, NULL, NULL, &error)) {
fprintf (stderr, "Delete failed: %s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./delete

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
C:\> delete

MongoDB shell を使用して、ドキュメントが正常に削除されたことを証明します。

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.count({"hello" : "world"})
0
>

MongoDB コレクション内のドキュメント数をカウントする方法は、検索操作を実行するのと同様です。 この例では、データベース「mydb」とコレクション「mycoll」内で{"hello" : "world"}に一致するドキュメントの数をカウントします。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
int64_t count;
mongoc_init ();
client =
mongoc_client_new ("mongodb://localhost:27017/?appname=count-example");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new_from_json (
(const uint8_t *) "{\"hello\" : \"world\"}", -1, &error);
count = mongoc_collection_count (
collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
if (count < 0) {
fprintf (stderr, "%s\n", error.message);
} else {
printf ("%" PRId64 "\n", count);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./count
1

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
C:\> count
1

このドライバーは、クライアント、データベース、およびコレクション構造で MongoDB コマンドを実行するためのヘルパー関数を提供します。 _simpleバリアントは、成功または失敗を示すブール値を返します。

この例では、データベース「mydb」に対してpingコマンドを実行します。

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>
int
main (void)
{
mongoc_client_t *client;
bson_error_t error;
bson_t *command;
bson_t reply;
char *str;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/?appname=executing-example");
command = BCON_NEW ("ping", BCON_INT32 (1));
if (mongoc_client_command_simple (client, "mydb", command, NULL, &reply, &error)) {
str = bson_as_canonical_extended_json (&reply, NULL);
printf ("%s\n", str);
bson_free (str);
} else {
fprintf (stderr, "Failed to run command: %s\n", error.message);
}
bson_destroy (command);
bson_destroy (&reply);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}

コードをコンパイルして実行します。

$ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./executing
{ "ok" : { "$numberDouble" : "1.0" }, "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } }, "signature" : { "hash" : { "$binary" : { "base64" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "subType" : "00" } }, "keyId" : { "$numberLong" : "0" } } }, "operationTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } } }

Windows の場合:

C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
C:\> executing
{ "ok" : { "$numberDouble" : "1.0" }, "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } }, "signature" : { "hash" : { "$binary" : { "base64" : "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "subType" : "00" } }, "keyId" : { "$numberLong" : "0" } } }, "operationTime" : { "$timestamp" : { "t" : 1682609211, "i" : 1 } } }

MongoDB C ドライバーは、操作の大部分でスレッド認識されません。 つまり、スレッドセーフ性を保証できるかどうかはプロファイラーに依存します。

ただし、 mongoc_client_Pool_t はスレッドセーフであり、スレッドセーフな方法で mongoc_client_t を取得するために使用されます。プールからクライアントを検索した後、クライアント構造は呼び出しスレッドによって所有されていると見なされる必要があります。スレッドが終了すると、クライアントはプールに戻されます。

sample-Pool.c
/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
* libmongoc-1.0) */
/* ./example-pool [CONNECTION_STRING] */
#include <mongoc/mongoc.h>
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mutex;
static bool in_shutdown = false;
static void *
worker (void *data)
{
mongoc_client_pool_t *pool = data;
mongoc_client_t *client;
bson_t ping = BSON_INITIALIZER;
bson_error_t error;
bool r;
BSON_APPEND_INT32 (&ping, "ping", 1);
while (true) {
client = mongoc_client_pool_pop (pool);
/* Do something with client. If you are writing an HTTP server, you
* probably only want to hold onto the client for the portion of the
* request performing database queries.
*/
r = mongoc_client_command_simple (client, "admin", &ping, NULL, NULL, &error);
if (!r) {
fprintf (stderr, "%s\n", error.message);
}
mongoc_client_pool_push (pool, client);
pthread_mutex_lock (&mutex);
if (in_shutdown || !r) {
pthread_mutex_unlock (&mutex);
break;
}
pthread_mutex_unlock (&mutex);
}
bson_destroy (&ping);
return NULL;
}
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
mongoc_uri_t *uri;
bson_error_t error;
mongoc_client_pool_t *pool;
pthread_t threads[10];
unsigned i;
void *ret;
pthread_mutex_init (&mutex, NULL);
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}

高度なトピックの情報を見つけるには、 C ドライバー ガイドの残りの部分 またはMongoDB の公式ドキュメントを参照してください。

For help with common issues, consult the Troubleshooting page. バグを報告したり、新機能をリクエストしたりするには、次の手順に従います。

戻る

プラットフォーム サポート