Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
C 드라이버
/

튜토리얼

이 가이드는 MongoDB C 드라이버에 대한 간략한 소개를 제공합니다.

For more information on the C API, please refer to the api.

특정 플랫폼에 MongoDB C 드라이버 를 설치하는 방법에 대한 자세한 지침은 설치 가이드 를 참조하세요.

이 튜토리얼의 예제를 실행하려면 기본 포트인 27017 의 localhost 에 MongoDB가 설치되어 실행 중이어야 합니다. 실행 중인지 확인하려면 MongoDB shell 을 사용하여 연결합니다.

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

libmongoc의 모든 기능과 유형은 하나의 헤더 파일에서 사용할 수 있습니다. mongoc/mongoc.h 을(를) 포함하기만 하면 됩니다.

#include <mongoc/mongoc.h>

The libmongoc installation includes a CMake config-file package, so you can use CMake's find_package command to import libmongoc's CMake target and link to libmongoc (as a shared library):

CMakeLists.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 CMake 타겟을 사용하세요:

# 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)

CMake를 사용하지 않는 경우 명령줄 에서 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)

CMake 또는 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 에 설치되어 있다고 가정하며, 필요에 따라 포함 디렉토리 를 변경합니다.)

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 가이드를 참조하세요.

Access MongoDB with a mongoc_client_t. It transparently connects to standalone servers, replica sets and sharded clusters on demand. To perform operations on a database or collection, create a mongoc_database_t or mongoc_collection_t struct from the mongoc_client_t.

At the start of an application, call mongoc_init before any other libmongoc functions. At the end, call the appropriate destroy function for each collection, database, or client handle, in reverse order from how they were constructed. Call mongoc_cleanup before exiting.

아래 예제에서는 localhost 에서 독립형 서버에 대한 연결을 설정하고 클라이언트 애플리케이션을 'connect-example'로 등록하고 간단한 명령을 수행합니다.

데이터베이스 작업에 대한 자세한 내용은 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 을 구문 분석하는 등 여러 가지 방법으로 구성할 수 있습니다.

A BSON document, represented as a bson_t in code, can be constructed one field at a time using libbson's append functions.

예를 들어 다음과 같은 문서를 만들 수 있습니다.

{
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;
}

See the libbson documentation for all of the types that can be appended to a bson_t.

BSON C Object Notation, BCON은 의도한 형식에 더 가까운 방식으로 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은 배열, 하위 문서 및 임의 필드를 만들 수 있습니다.

For single documents, BSON can be created from JSON strings via bson_new_from_json.

#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;
}

To initialize BSON from a sequence of JSON documents, use bson_json_reader_t.

이 섹션에서는 C 드라이버 를 사용하여 MongoDB 와 상호 작용 하는 기본 사항을 설명합니다.

To insert documents into a collection, first obtain a handle to a mongoc_collection_t via a mongoc_client_t. Then, use mongoc_collection_insert_one to add BSON documents to the collection. This example inserts into the database "mydb" and collection "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" }
>

To query a MongoDB collection with the C driver, use the function mongoc_collection_find_with_opts. This returns a cursor to the matching documents. The following examples iterate through the result cursors and print the matches to stdout as JSON strings.

문서를 쿼리 지정자로 사용합니다. 예를 들어,

{ "color" : "red" }

은(는) 값이 '빨간색'인 '색상'이라는 필드가 있는 모든 문서와 일치합니다. 빈 문서 {} 를 사용하여 모든 문서를 일치시킬 수 있습니다.

이 첫 번째 예제에서는 빈 쿼리 지정자를 사용하여 데이터베이스 '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" }

This code snippet gives an example of using mongoc_collection_update_one to update the fields of a document.

다음 예제에서는 '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" }
>

This example illustrates the use of mongoc_collection_delete_one to delete a document.

다음 코드는 샘플 문서 를 데이터베이스 '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'에 대해 명령을 실행합니다.

#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 드라이버는 대부분의 작업에서 스레드를 인식하지 않습니다. 즉, 스레드 안전성을 보장하는 것은 프로그래머의 몫입니다.

However, mongoc_client_pool_t is thread-safe and is used to fetch a mongoc_client_t in a thread-safe manner. After retrieving a client from the pool, the client structure should be considered owned by the calling thread. When the thread is finished, the client should be placed back into the pool.

example-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 설명서 를 참조하세요.

일반적인 문제에 대한 도움이 필요하면 문제 해결 페이지를 참조하세요. 버그를 신고하거나 새로운 기능 을 요청 하려면 다음 안내를 따르세요.

돌아가기

플랫폼 지원

이 페이지의 내용