Esta guía ofrece una breve introducción al controlador MongoDB C.
Para obtener más información sobre la API de C, consulte la API.
Instalación
Para obtener instrucciones detalladas sobre la instalación del controlador MongoDB C en una plataforma en particular, consulte la Guía de instalación.
Iniciando MongoDB
Para ejecutar los ejemplos de este tutorial, MongoDB debe estar instalado y ejecutándose en localhost En el puerto predeterminado, 27017. Para comprobar si está en funcionamiento, conéctese con el shell de MongoDB.
$ mongosh --host localhost --port 27017 --quiet Enterprise rs0 [direct: primary] test> db.version() 7.0.0 >
Incluye y enlaza libmongoc en tu programa en C
Incluir mongoc.h
Todas las funciones y tipos de libmongoc están disponibles en un solo archivo de encabezado. Simplemente incluya mongoc/mongoc.h:
CMake
La instalación de libmongoc incluye un paquete de archivos de configuración de CMake, por lo que puede usar el comando find_package de CMake para importar el destino CMake de libmongoc y vincularlo a libmongoc (como una biblioteca compartida):
# 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)
También puedes usar libmongoc como una biblioteca estática en su lugar: usa el objetivo CMake mongo::mongoc_static:
# 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)
pkg-config
Si no está usando CMake, use pkg-config en la línea de comando para establecer las rutas de encabezado y biblioteca:
gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)
O para vincular estáticamente a libmongoc:
gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)
Especificación manual de rutas de encabezado e inclusión
Si no utiliza CMake o pkg-config, las rutas y librerías pueden gestionarse manualmente.
$ 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 }
Para usuarios de Windows, el código se puede compilar y ejecutar con los siguientes comandos. (Esto supone que el controlador C de MongoDB está instalado en C:\mongo-c-driver; modifique el directorio de inclusión según sea necesario).
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 }
Utilice libmongoc en un proyecto de Microsoft Visual Studio
Consultela guía de libmongoc y Visual Studio.
Estableciendo una conexión
Acceda a MongoDB con un mongoc_client_t. Se conecta de forma transparente a servidores independientes, conjuntos de réplicas y clústeres fragmentados bajo demanda. Para realizar operaciones en una base de datos o colección, cree una estructura mongoc_database_t o mongoc_collection_t a partir de mongoc_client_t.
Al iniciar una aplicación, llame a mongoc_init antes de cualquier otra función de libmongoc. Al final, llame a la función de destrucción correspondiente para cada colección, base de datos o identificador de cliente, en orden inverso al de su construcción. Llame a mongoc_cleanup antes de salir.
El siguiente ejemplo establece una conexión a un servidor independiente en localhost, registra la aplicación cliente como "connect-example" y ejecuta un comando simple.
Puede encontrar más información sobre las operaciones de base de datos en las secciones "Operaciones CRUD" y "Ejecución de comandos". Puede encontrar ejemplos de conexión a conjuntos de réplicas y clústeres fragmentados en la página "Conexiones avanzadas", mientras que ejemplos de compresión de datos se encuentran en la página "Compresión de datos".
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; }
Creación de documentos BSON
Los documentos se almacenan en el formato de datos de MongoDB, BSON. El controlador de C usa libbson para crear documentos BSON. Hay varias maneras de construirlos: añadiendo pares clave-valor, usando BCON o analizando JSON.
Añadiendo BSON
Un documento BSON, representado como bson_t en el código, se puede construir un campo a la vez utilizando las funciones de anexión de libbson.
Por ejemplo, para crear un documento como este:
{ 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" } ] }
Utilice el siguiente código:
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; }
Consulte la documentación de libbson para conocer todos los tipos que se pueden agregar a un bson_t.
Usando BCON
BSON C Object Notation, BCON para abreviar, es una forma alternativa de construir documentos BSON de una manera más cercana al formato deseado. Tiene menos seguridad de tipos que las funciones de anexar de BSON, pero resulta en menos código.
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; }
Tenga en cuenta que BCON puede crear matrices, subdocumentos y campos arbitrarios.
Creando BSON a partir de JSON
Para documentos individuales, se puede crear BSON a partir de cadenas JSON mediante bson_new_from_json.
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; }
Para inicializar BSON a partir de una secuencia de documentos JSON, utiliza bson_json_reader_t.
Operaciones CRUD básicas
Esta sección demuestra los conceptos básicos del uso del controlador C para interactuar con MongoDB.
Insertar un documento
Para insertar documentos en una colección, primero obtenga un identificador mongoc_collection_t de mongoc_client_t mediante. Luego, use mongoc_collection_insert_one para agregar documentos BSON a la colección. Este ejemplo inserta en la base de datos "mydb" y la colección "mycoll".
Una vez finalizado, asegúrese de que las estructuras asignadas se liberen utilizando sus respectivas funciones de destrucción.
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; }
Compila el código y ejecútalo:
$ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0) $ ./insert
En Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c C:\> insert
Para verificar que la inserción se realizó correctamente, conéctese con el shell de MongoDB.
$ mongo MongoDB shell version: 3.0.6 connecting to: test > use mydb switched to db mydb > db.mycoll.find() { "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" } >
Encontrar un documento
Para consultar una colección de MongoDB con el controlador C, utilice la función mongoc_collection_find_with_opts. Esta función devuelve un cursor a los documentos coincidentes. Los siguientes ejemplos iteran sobre los cursores de resultados e imprimen las coincidencias en stdout como cadenas JSON.
Utilice un documento como especificador de consulta; por ejemplo,
{ "color" : "red" }
Coincidirá con cualquier documento cuyo campo "color" tenga el valor "rojo". Se puede usar un documento vacío {} para comparar todos los documentos.
Este primer ejemplo utiliza un especificador de consulta vacío para encontrar todos los documentos en la base de datos "mydb" y la colección "mycoll".
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; }
Compila el código y ejecútalo:
$ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0) $ ./find { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
En 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" }
Para buscar un documento específico, agregue un especificador a query. Este ejemplo agrega una llamada a BSON_APPEND_UTF8() para buscar todos los documentos que coincidan con {"hello" : "world"}.
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" }
Actualizar un documento
Este snippet de código muestra un ejemplo del uso de mongoc_collection_update_one para actualizar los campos de un documento.
Usando la base de datos "mydb", el siguiente ejemplo inserta un documento de ejemplo en la colección "mycoll". Luego, usando su campo _id, el documento se actualiza con valores diferentes y un nuevo campo.
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; }
Compila el código y ejecútalo:
$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0) $ ./update
En 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" }
Para verificar que la actualización se realizó correctamente, conéctese al shell de MongoDB.
$ 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" } >
Eliminar un documento
Este ejemplo ilustra el uso de mongoc_collection_delete_one para eliminar un documento.
El siguiente código inserta un documento de ejemplo en la base de datos "mydb" y la colección "mycoll". A continuación, elimina todos los documentos que coinciden con {"hello" : "world"}.
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; }
Compila el código y ejecútalo:
$ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0) $ ./delete
En Windows:
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c C:\> delete
Utilice el shell de MongoDB para demostrar que los documentos se han eliminado correctamente.
$ mongo MongoDB shell version: 3.0.6 connecting to: test > use mydb switched to db mydb > db.mycoll.count({"hello" : "world"}) 0 >
Contar documentos
Contar el número de documentos en una colección de MongoDB es similar a realizar una búsqueda. Este ejemplo cuenta el número de documentos que coinciden con {"hello" : "world"} en la base de datos "mydb" y la colección "mycoll".
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; }
Compila el código y ejecútalo:
$ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0) $ ./count 1
En 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
Ejecutando comandos
El controlador proporciona funciones auxiliares para ejecutar comandos MongoDB en estructuras de cliente, base de datos y colección. Las variantes _simple devuelven valores booleanos que indican éxito o fracaso.
Este ejemplo ejecuta el comando ping contra la base de datos "mydb".
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; }
Compila el código y ejecútalo:
$ 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 } } }
En 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 } } }
Enhebrado
El controlador C de MongoDB no reconoce subprocesos en la gran mayoría de sus operaciones. Esto significa que es responsabilidad del programador garantizar la seguridad de los subprocesos.
Sin embargo, mongoc_client_pool_t es seguro para subprocesos y se utiliza para obtener un mongoc_client_t de forma segura. Tras recuperar un cliente del pool, la estructura del cliente debe considerarse propiedad del subproceso que lo llama. Al finalizar el subproceso, el cliente debe volver al pool.
/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs * libmongoc-1.0) */ /* ./example-pool [CONNECTION_STRING] */ 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; }
Próximos pasos
Para encontrar información sobre temas avanzados, consulte el resto de la guía del controlador C o la documentación oficial de MongoDB.
Para obtener ayuda con problemas comunes, consulte la página de Solución de problemas. Para reportar un error o solicitar una nueva funcionalidad, siga estas instrucciones.