A Voyage AI se une ao MongoDB para impulsionar aplicativos de AI mais precisos e confiáveis no Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Desenvolvedor do MongoDB
Centro de desenvolvedores do MongoDB
chevron-right
Produtos
chevron-right
Atlas
chevron-right

Introdução ao MongoDB e C

Diego Freniche12 min read • Published Mar 24, 2023 • Updated Sep 17, 2024
AtlasC
SNIPPET
Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Introdução ao MongoDB e C

Neste artigo, instalaremos o driverdoMongoDB C no macOS e usaremos esse driver para escrever alguns exemplos de aplicativos de console que podem interagir com seus dados do MongoDB executando operações CRUD básicas. Usaremos o Visual Studio Code para digitar o código e a linha de comando para compilar e executar nossos programas. Se você quiser experimentar agora, todo o código-fonte está no repositório GitHub.

Sumário

Pré-requisitos

  1. Uma conta do MongoDB Atlas com um cluster criado.
  2. O conjunto de dados de amostra carregado no Atlas cluster (ou você pode modificar o código de amostra para utilizar seu próprio banco de dados e collection).
  3. O endereço IP da sua máquina está na lista de permissões. Nota: Você pode adicionar 0.0.0.0/0 como o endereço IP, que deve permitir o acesso de qualquer máquina. Essa configuração não é recomendada para uso em produção.

VS Code, extensões C, Xcode

  1. Usaremos o Visual Studio Code, disponível no macOS, Windows e Linux, porque ele tem suporte oficial para código C. Basta baixar e instalar a versão apropriada.
  2. Precisamos das extensões C, que serão sugeridas quando você abrir um arquivo C pela primeira vez. Você também pode abrir extensões e procurar por "C/C++" e instalá-las. Isso instalará várias extensões: C/C++, C/C++ Themes e CMake.
  3. A última etapa é garantir que tenhamos um compilador C. Para isso,instale o Xcode da Mac App Store ou execute em um terminal:
1$ xcode-select --install
Embora possamos usar oCMake para criar nossos aplicativos C (e você tenha instruções detalhadas sobre como fazer isso), usaremos o VS Code para digitar nosso código e o terminal para criar e executar nossos programas.

Instalando o driver C

No macOS, se tivermos o gerenciador de pacotes homebrew instalado (o que você deve fazer), basta abrir um terminal e digitar:
1$ brew install mongo-c-driver
Você também pode baixar o código-fonte e construir o driver, mas usar brew é muito mais conveniente.

Configurando extensões do VS Code

Para fazer o preenchimento automático funcionar no VS Code, precisamos alterar a configuração da extensão para garantir que ela "veja" essas novas bibliotecas instaladas. Queremos alterar nosso INCLUDE_PATH para permitir que o IntelliSense verifique nosso código enquanto o digita e possa criar nosso aplicativo a partir do VS Code.
Para fazer isso, no VS Code, abra a pasta oculta.vscodee clique em c_cpp_properties.json e adicione estas linhas:
1{
2 "configurations": [
3 {
4 "name": "Mac",
5 "includePath": [
6 "/usr/local/include/libbson-1.0/**",
7 "/usr/local/include/libmongoc-1.0/**",
8 "${workspaceFolder}/**"
9 ],
10...
11 }
12 ]
13}
Agora, abra tarefas.json e adicione estas linhas à matriz args:
1"-I/usr/local/include/libmongoc-1.0",
2"-I/usr/local/include/libbson-1.0",
3"-lmongoc-1.0",
4"-lbson-1.0",`
Com eles, estamos informando ao VS Code onde encontrar as bibliotecas C do MongoDB para que ele possa compilar e verificar nosso código à medida que digitamos.

Olá, MongoDB!

O código-fonte está disponível no GitHub.

Configurando o cliente e enviando ping para o MongoDB Atlas

Vamos começar com um programa simples que se conecta ao MongoDB Atlas cluster e faz pings no servidor. Para isso, precisamos obter a cadeia de conexão (URI) para o MongoDB Atlas cluster e adicioná-la em nosso código. A melhor maneira é criar uma nova variável de ambiente com a chave "MONGODB_URI " e valorizar a connection string (URI). É uma boa prática manter a string de conexão dissociada do código, mas, neste exemplo, para simplificar, teremos nossa string de conexão codificada.
Incluímos o driver MongoDB e enviamos um comando "echo" de nossa funçãomain. Este exemplo mostra como inicializar o cliente MongoDB C, como criar um comando, manipular JSON (neste caso, BCON, Notação de objetoBSON C), enviar um comando, processar a resposta e o erro e liberar qualquer memória usada.
1// hello_mongo.c
2#include <mongoc/mongoc.h>
3
4int main(int argc, char const *argv[]) {
5 // your MongoDB URI connection string
6 const char *uri_string = "mongodb+srv://<connection string>";
7 // MongoDB URI created from above string
8 mongoc_uri_t *uri;
9 // MongoDB Client, used to connect to the DB
10 mongoc_client_t *client;
11 // Command to be sent, and reply
12 bson_t *command, reply;
13 // Error management
14 bson_error_t error;
15 // Misc
16 char *str;
17 bool retval;
18
19 /*
20 * Required to initialize libmongoc's internals
21 */
22 mongoc_init();
23
24 /*
25 * Optionally get MongoDB URI from command line
26 */
27 if (argc > 1) {
28 uri_string = argv[1];
29 }
30
31 /*
32 * Safely create a MongoDB URI object from the given string
33 */
34 uri = mongoc_uri_new_with_error(uri_string, &error);
35 if (!uri) {
36 fprintf(stderr,
37 "failed to parse URI: %s\n"
38 "error message: %s\n",
39 uri_string, error.message);
40 return EXIT_FAILURE;
41 }
42
43 /*
44 * Create a new client instance, here we use the uri we just built
45 */
46 client = mongoc_client_new_from_uri(uri);
47 if (!client) {
48 return EXIT_FAILURE;
49 }
50
51 /*
52 * Register the application name so we can track it in the profile logs
53 * on the server. This can also be done from the URI (see other examples).
54 */
55 mongoc_client_set_appname(client, "connect-example");
56
57 /*
58 * Do work. This example pings the database and prints the result as JSON
59 * BCON == BSON C Object Notation
60 */
61 command = BCON_NEW("ping", BCON_INT32(1));
62
63 // we run above command on our DB, using the client. We get reply and error
64 // (if any)
65 retval = mongoc_client_command_simple(client, "admin", command, NULL, &reply,
66 &error);
67
68 // mongoc_client_command_simple returns false and sets error if there are
69 // invalid arguments or a server or network error.
70 if (!retval) {
71 fprintf(stderr, "%s\n", error.message);
72 return EXIT_FAILURE;
73 }
74
75 // if we're here, there's a JSON response
76 str = bson_as_json(&reply, NULL);
77 printf("%s\n", str);
78
79 /*
80 * Clean up memory
81 */
82 bson_destroy(&reply);
83 bson_destroy(command);
84 bson_free(str);
85
86 /*
87 * Release our handles and clean up libmongoc
88 */
89
90 mongoc_uri_destroy(uri);
91 mongoc_client_destroy(client);
92 mongoc_cleanup();
93
94 return EXIT_SUCCESS;
95}

Compilando e executando nosso código

Embora possamos usar métodos muito mais sofisticados para compilar e executar nosso código, como este é apenas um arquivo de código-fonte C e estamos usando apenas algumas dependências, vou compilar a partir da linha de comando usando o bom e velho gcc:
1gcc -o hello_mongoc hello_mongoc.c \
2 -I/usr/local/include/libbson-1.0
3 -I/usr/local/include/libmongoc-1.0 \
4 -lmongoc-1.0 -lbson-1.0
Para executar o código, basta chamar o binário construído:
1./hello_mongo
No repositório que acompanha esta postagem, você encontrará um shell script que cria e executa todos os exemplosde uma só vez.

Conectando ao banco de dados e listando todas as coleções

Agora que temos o esqueleto de um aplicativo C, podemos começar a usar nosso banco de dados. Nesse caso, nos conectaremos ao banco de dados sample_mflixe listaremos todas as coleções lá.
Após conectar ao banco de dados, listamos todas as conexões com um simples loop forapós obter todos os nomes de collection commongoc_database_get_collection_names.
1if ((collection_names =
2 mongoc_database_get_collection_names(database, &error))) {
3 for (i = 0; collection_names[i]; i++) {
4 printf("%s\n", collection_names[i]);
5 }
6
7 }
A amostra completa segue.
1// list_collections.c
2#include <mongoc/mongoc.h>
3
4int main(int argc, char const *argv[]) {
5 // your MongoDB URI connection string
6 const char *uri_string = "mongodb+srv://<connection string>";
7
8 // MongoDB URI created from above string
9 mongoc_uri_t *uri;
10 // MongoDB Client, used to connect to the DB
11 mongoc_client_t *client;
12
13 // Error management
14 bson_error_t error;
15
16 mongoc_database_t *database;
17 mongoc_collection_t *collection;
18 char **collection_names;
19 unsigned i;
20
21 /*
22 * Required to initialize libmongoc's internals
23 */
24 mongoc_init();
25
26 /*
27 * Safely create a MongoDB URI object from the given string
28 */
29 uri = mongoc_uri_new_with_error(uri_string, &error);
30 if (!uri) {
31 fprintf(stderr,
32 "failed to parse URI: %s\n"
33 "error message: %s\n",
34 uri_string, error.message);
35 return EXIT_FAILURE;
36 }
37
38 /*
39 * Create a new client instance, here we use the uri we just built
40 */
41 client = mongoc_client_new_from_uri(uri);
42 if (!client) {
43 return EXIT_FAILURE;
44 }
45
46 /*
47 * Register the application name so we can track it in the profile logs
48 * on the server. This can also be done from the URI (see other examples).
49 */
50 mongoc_client_set_appname(client, "connect-example");
51
52 /*
53 * Get a handle on the database "db_name" and collection "coll_name"
54 */
55 database = mongoc_client_get_database(client, "sample_mflix");
56
57// getting all collection names, here we're not passing in any options
58 if ((collection_names = mongoc_database_get_collection_names_with_opts(
59 database, NULL, &error))) {
60
61 for (i = 0; collection_names[i]; i++) {
62 printf("%s\n", collection_names[i]);
63 }
64
65 } else {
66 fprintf(stderr, "Error: %s\n", error.message);
67 return EXIT_FAILURE;
68 }
69
70 /*
71 * Release our handles and clean up libmongoc
72 */
73
74 mongoc_uri_destroy(uri);
75 mongoc_client_destroy(client);
76 mongoc_cleanup();
77
78 return EXIT_SUCCESS;
79}
Se compilarmos e executarmos, obteremos esta saída:
1$ ./list_collections
2sessions
3users
4theaters
5movies
6comments

Criando um objeto JSON em C

Por ser um banco de dados baseado em documentos, a criação de documentos JSON é crucial para qualquer aplicativo que interaja com o MongoDB. Como este é um código C, não usamos JSON. Em vez disso, usamos BCON (notação de objetoBSON C, como mencionado acima). Para criar um novo documento, chamamos BCON_NEWe, para convertê-lo em uma string C, chamamos bson_as_canonical_extended_json.
1// bcon.c
2// https://mongoc.org/libmongoc/current/tutorial.html#using-bcon
3#include <mongoc/mongoc.h>
4
5// Creating the JSON doc:
6/*
7{
8 born : ISODate("1906-12-09"),
9 died : ISODate("1992-01-01"),
10 name : {
11 first : "Grace",
12 last : "Hopper"
13 },
14 languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
15 degrees: [ { degree: "BA", school: "Vassar" },
16 { degree: "PhD", school: "Yale" } ]
17}
18*/
19
20int main(int argc, char *argv[]) {
21 struct tm born = {0};
22 struct tm died = {0};
23 bson_t *document;
24 char *str;
25
26 born.tm_year = 6;
27 born.tm_mon = 11;
28 born.tm_mday = 9;
29
30 died.tm_year = 92;
31 died.tm_mon = 0;
32 died.tm_mday = 1;
33
34 // document = BCON_NEW("born", BCON_DATE_TIME(mktime(&born) * 1000),
35 // "died", BCON_DATE_TIME(mktime(&died) * 1000),
36 // "name", "{",
37 // "first", BCON_UTF8("Grace"),
38 // "last", BCON_UTF8("Hopper"),
39 // "}",
40 // "languages", "[",
41 // BCON_UTF8("MATH-MATIC"),
42 // BCON_UTF8("FLOW-MATIC"),
43 // BCON_UTF8("COBOL"),
44 // "]",
45 // "degrees", "[",
46 // "{", "degree", BCON_UTF8("BA"), "school",
47 // BCON_UTF8("Vassar"), "}",
48 // "{", "degree", BCON_UTF8("PhD"),"school",
49 // BCON_UTF8("Yale"), "}",
50 // "]");
51
52 document = BCON_NEW("born", BCON_DATE_TIME(mktime(&born) * 1000), "died",
53 BCON_DATE_TIME(mktime(&died) * 1000), "name", "{",
54 "first", BCON_UTF8("Grace"), "last", BCON_UTF8("Hopper"),
55 "}", "languages", "[", BCON_UTF8("MATH-MATIC"),
56 BCON_UTF8("FLOW-MATIC"), BCON_UTF8("COBOL"), "]",
57 "degrees", "[", "{", "degree", BCON_UTF8("BA"), "school",
58 BCON_UTF8("Vassar"), "}", "{", "degree", BCON_UTF8("PhD"),
59 "school", BCON_UTF8("Yale"), "}", "]");
60
61 /*
62 * Print the document as a JSON string.
63 */
64 str = bson_as_canonical_extended_json(document, NULL);
65 printf("%s\n", str);
66 bson_free(str);
67
68 /*
69 * Clean up allocated bson documents.
70 */
71 bson_destroy(document);
72 return 0;
73}

CRUD no MongoDB usando o driver C

Agora que abordamos os fundamentos da conexão com o MongoDB, vamos dar uma olhada em como manipular dados.

Query de dados

Provavelmente, a função mais usada de qualquer banco de dados é a recuperação rápida de dados. Na maioria dos casos de uso, gastamos muito mais tempo acessando dados do que inserindo ou atualizando esses mesmos dados. Nesse caso, depois de criar nossa conexão com o cliente MongoDB, chamamos mongoc_collection_find_with_opts, que encontrará dados com base em uma consulta que podemos passar. Quando tivermos os resultados, podemos iterar pelo cursor retornado e fazer algo com esses dados:
1// All movies from 1984!
2 BSON_APPEND_INT32(query, "year", 1984);
3 cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
4
5 while (mongoc_cursor_next(cursor, &query)) {
6 str = bson_as_canonical_extended_json(query, NULL);
7 printf("%s\n", str);
8 bson_free(str);
9 }
A amostra completa segue.
1// find.c
2#include "URI.h"
3#include <mongoc/mongoc.h>
4
5int main(int argc, char const *argv[]) {
6 // your MongoDB URI connection string
7 const char *uri_string = MY_MONGODB_URI;
8 // MongoDB URI created from above string
9 mongoc_uri_t *uri;
10 // MongoDB Client, used to connect to the DB
11 mongoc_client_t *client;
12
13 // Error management
14 bson_error_t error;
15
16 mongoc_collection_t *collection;
17 char **collection_names;
18 unsigned i;
19
20 // Query object
21 bson_t *query;
22 mongoc_cursor_t *cursor;
23
24 char *str;
25
26 /*
27 * Required to initialize libmongoc's internals
28 */
29 mongoc_init();
30
31 /*
32 * Safely create a MongoDB URI object from the given string
33 */
34 uri = mongoc_uri_new_with_error(uri_string, &error);
35 if (!uri) {
36 fprintf(stderr,
37 "failed to parse URI: %s\n"
38 "error message: %s\n",
39 uri_string, error.message);
40 return EXIT_FAILURE;
41 }
42
43 /*
44 * Create a new client instance, here we use the uri we just built
45 */
46 client = mongoc_client_new_from_uri(uri);
47 if (!client) {
48 puts("Error connecting!");
49 return EXIT_FAILURE;
50 }
51
52 /*
53 * Register the application name so we can track it in the profile logs
54 * on the server. This can also be done from the URI (see other examples).
55 */
56 mongoc_client_set_appname(client, "connect-example");
57
58 /*
59 * Get a handle on the database "db_name" and collection "coll_name"
60 */
61 collection = mongoc_client_get_collection(client, "sample_mflix", "movies");
62
63 query = bson_new();
64
65 // All movies from 1984!
66 BSON_APPEND_INT32(query, "year", 1984);
67 cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);
68
69 while (mongoc_cursor_next(cursor, &query)) {
70 str = bson_as_canonical_extended_json(query, NULL);
71 printf("%s\n", str);
72 bson_free(str);
73 }
74
75 /*
76 * Release our handles and clean up libmongoc
77 */
78
79 bson_destroy(query);
80
81 mongoc_collection_destroy(collection);
82 mongoc_uri_destroy(uri);
83 mongoc_client_destroy(client);
84 mongoc_cleanup();
85
86 return EXIT_SUCCESS;
87}

Inserindo um novo documento

OK, sabemos ler dados, mas que tal inserir dados novos em nosso MongoDB database? É fácil! Acabamos de criar um BSON para ser inserido e chamar mongoc_collection_insert_one.
1doc = bson_new();
2 bson_oid_init(&oid, NULL);
3 BSON_APPEND_OID(doc, "_id", &oid);
4 BSON_APPEND_UTF8(doc, "name", "My super new picture");
5
6 if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
7 fprintf(stderr, "%s\n", error.message);
8 }
A amostra completa segue.
1// insert.c
2#include "URI.h"
3#include <mongoc/mongoc.h>
4
5int main(int argc, char const *argv[]) {
6 // your MongoDB URI connection string
7 const char *uri_string = MY_MONGODB_URI;
8 // MongoDB URI created from above string
9 mongoc_uri_t *uri;
10 // MongoDB Client, used to connect to the DB
11 mongoc_client_t *client;
12
13 // Error management
14 bson_error_t error;
15
16 mongoc_collection_t *collection;
17 char **collection_names;
18 unsigned i;
19
20 // Object id and BSON doc
21 bson_oid_t oid;
22 bson_t *doc;
23
24 char *str;
25
26 /*
27 * Required to initialize libmongoc's internals
28 */
29 mongoc_init();
30
31 /*
32 * Safely create a MongoDB URI object from the given string
33 */
34 uri = mongoc_uri_new_with_error(uri_string, &error);
35 if (!uri) {
36 fprintf(stderr,
37 "failed to parse URI: %s\n"
38 "error message: %s\n",
39 uri_string, error.message);
40 return EXIT_FAILURE;
41 }
42
43 /*
44 * Create a new client instance, here we use the uri we just built
45 */
46 client = mongoc_client_new_from_uri(uri);
47 if (!client) {
48 return EXIT_FAILURE;
49 }
50
51 /*
52 * Register the application name so we can track it in the profile logs
53 * on the server. This can also be done from the URI (see other examples).
54 */
55 mongoc_client_set_appname(client, "connect-example");
56
57 /*
58 * Get a handle on the database "db_name" and collection "coll_name"
59 */
60 collection = mongoc_client_get_collection(client, "sample_mflix", "movies");
61
62 doc = bson_new();
63 bson_oid_init(&oid, NULL);
64 BSON_APPEND_OID(doc, "_id", &oid);
65 BSON_APPEND_UTF8(doc, "name", "My super new picture");
66
67 if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
68 fprintf(stderr, "%s\n", error.message);
69 } else {
70 printf("Document inserted!");
71 /*
72 * Print the document as a JSON string.
73 */
74 str = bson_as_canonical_extended_json(doc, NULL);
75 printf("%s\n", str);
76 bson_free(str);
77 }
78
79 /*
80 * Release our handles and clean up libmongoc
81 */
82
83 mongoc_collection_destroy(collection);
84 mongoc_uri_destroy(uri);
85 mongoc_client_destroy(client);
86 mongoc_cleanup();
87
88 return EXIT_SUCCESS;
89}

Excluindo um documento

Para excluir um documento, chamamos mongoc_collection_delete_one. Precisamos passar um documento contendo a query para restringir os documentos que queremos localizar e excluir.
1doc = bson_new();
2 BSON_APPEND_OID(doc, "_id", &oid);
3
4 if (!mongoc_collection_delete_one(collection, doc, NULL, NULL, &error)) {
5 fprintf(stderr, "Delete failed: %s\n", error.message);
6 }
A amostra completa segue.
1// delete.c
2#include "URI.h"
3#include <mongoc/mongoc.h>
4
5int main(int argc, char const *argv[]) {
6 // your MongoDB URI connection string
7 const char *uri_string = MY_MONGODB_URI;
8 // MongoDB URI created from above string
9 mongoc_uri_t *uri;
10 // MongoDB Client, used to connect to the DB
11 mongoc_client_t *client;
12
13 // Error management
14 bson_error_t error;
15
16 mongoc_collection_t *collection;
17 char **collection_names;
18 unsigned i;
19
20 // Object id and BSON doc
21 bson_oid_t oid;
22 bson_t *doc;
23
24 char *str;
25
26 /*
27 * Required to initialize libmongoc's internals
28 */
29 mongoc_init();
30
31 /*
32 * Safely create a MongoDB URI object from the given string
33 */
34 uri = mongoc_uri_new_with_error(uri_string, &error);
35 if (!uri) {
36 fprintf(stderr,
37 "failed to parse URI: %s\n"
38 "error message: %s\n",
39 uri_string, error.message);
40 return EXIT_FAILURE;
41 }
42
43 /*
44 * Create a new client instance, here we use the uri we just built
45 */
46 client = mongoc_client_new_from_uri(uri);
47 if (!client) {
48 return EXIT_FAILURE;
49 }
50
51 /*
52 * Register the application name so we can track it in the profile logs
53 * on the server. This can also be done from the URI (see other examples).
54 */
55 mongoc_client_set_appname(client, "connect-example");
56
57 /*
58 * Get a handle on the database "db_name" and collection "coll_name"
59 */
60 collection = mongoc_client_get_collection(client, "sample_mflix", "movies");
61
62 // Let's insert one document in this collection!
63 doc = bson_new();
64 bson_oid_init(&oid, NULL);
65 BSON_APPEND_OID(doc, "_id", &oid);
66 BSON_APPEND_UTF8(doc, "name", "My super new picture");
67
68 if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
69 fprintf(stderr, "%s\n", error.message);
70 } else {
71 printf("Document inserted!");
72 /*
73 * Print the document as a JSON string.
74 */
75 str = bson_as_canonical_extended_json(doc, NULL);
76 printf("%s\n", str);
77 bson_free(str);
78 }
79
80 bson_destroy(doc);
81
82 // Delete the inserted document!
83
84 doc = bson_new();
85 BSON_APPEND_OID(doc, "_id", &oid);
86
87 if (!mongoc_collection_delete_one(collection, doc, NULL, NULL, &error)) {
88 fprintf(stderr, "Delete failed: %s\n", error.message);
89 } else {
90 puts("Document deleted!");
91 }
92
93 /*
94 * Release our handles and clean up libmongoc
95 */
96
97 mongoc_collection_destroy(collection);
98 mongoc_uri_destroy(uri);
99 mongoc_client_destroy(client);
100 mongoc_cleanup();
101
102 return EXIT_SUCCESS;
103}

Atualizando um documento

Finalmente, para atualizar um documento, precisamos fornecer a consulta para encontrar o documento a ser atualizado e um documento com os campos que queremos alterar.
1query = BCON_NEW("_id", BCON_OID(&oid));
2update =
3 BCON_NEW("$set", "{", "name", BCON_UTF8("Super new movie was boring"),
4 "updated", BCON_BOOL(true), "}");
5
6if (!mongoc_collection_update_one(collection, query, update, NULL, NULL,
7 &error)) {
8 fprintf(stderr, "%s\n", error.message);
9}
A amostra completa segue.
1// update.c
2#include "URI.h"
3#include <mongoc/mongoc.h>
4
5int main(int argc, char const *argv[]) {
6 // your MongoDB URI connection string
7 const char *uri_string = MY_MONGODB_URI;
8 // MongoDB URI created from above string
9 mongoc_uri_t *uri;
10 // MongoDB Client, used to connect to the DB
11 mongoc_client_t *client;
12
13 // Error management
14 bson_error_t error;
15
16 mongoc_collection_t *collection;
17 char **collection_names;
18 unsigned i;
19
20 // Object id and BSON doc
21 bson_oid_t oid;
22 bson_t *doc;
23
24 // document to update and query to find it
25 bson_t *update = NULL;
26 bson_t *query = NULL;
27 char *str;
28
29 /*
30 * Required to initialize libmongoc's internals
31 */
32 mongoc_init();
33
34 /*
35 * Safely create a MongoDB URI object from the given string
36 */
37 uri = mongoc_uri_new_with_error(uri_string, &error);
38 if (!uri) {
39 fprintf(stderr,
40 "failed to parse URI: %s\n"
41 "error message: %s\n",
42 uri_string, error.message);
43 return EXIT_FAILURE;
44 }
45
46 /*
47 * Create a new client instance, here we use the uri we just built
48 */
49 client = mongoc_client_new_from_uri(uri);
50 if (!client) {
51 return EXIT_FAILURE;
52 }
53
54 /*
55 * Register the application name so we can track it in the profile logs
56 * on the server. This can also be done from the URI (see other examples).
57 */
58 mongoc_client_set_appname(client, "connect-example");
59
60 /*
61 * Get a handle on the database "db_name" and collection "coll_name"
62 */
63 collection = mongoc_client_get_collection(client, "sample_mflix", "movies");
64
65 // we create a new BSON Document
66 doc = bson_new();
67 bson_oid_init(&oid, NULL);
68 BSON_APPEND_OID(doc, "_id", &oid);
69 BSON_APPEND_UTF8(doc, "name", "My super new movie");
70
71 // Then we insert it in the movies collection
72 if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error)) {
73 fprintf(stderr, "%s\n", error.message);
74 } else {
75 printf("Document inserted!\n");
76 /*
77 * Print the document as a JSON string.
78 */
79 str = bson_as_canonical_extended_json(doc, NULL);
80 printf("%s\n", str);
81 bson_free(str);
82
83 // now we search for that document to update it
84 query = BCON_NEW("_id", BCON_OID(&oid));
85 update =
86 BCON_NEW("$set", "{", "name", BCON_UTF8("Super new movie was boring"),
87 "updated", BCON_BOOL(true), "}");
88
89 if (!mongoc_collection_update_one(collection, query, update, NULL, NULL,
90 &error)) {
91 fprintf(stderr, "%s\n", error.message);
92 } else {
93 printf("Document edited!\n");
94 str = bson_as_canonical_extended_json(update, NULL);
95 printf("%s\n", str);
96 }
97 }
98
99 /*
100 * Release our handles and clean up libmongoc
101 */
102
103 if (doc) {
104 bson_destroy(doc);
105 }
106 if (query) {
107 bson_destroy(query);
108 }
109 if (update) {
110 bson_destroy(update);
111 }
112
113 mongoc_collection_destroy(collection);
114 mongoc_uri_destroy(uri);
115 mongoc_client_destroy(client);
116 mongoc_cleanup();
117
118 return EXIT_SUCCESS;
119}

Encerrando

Com este artigo, abordamos a instalação do driver MongoDB C, configurando o VS Code como nosso editor e configurando outras ferramentas. Em seguida, criamos alguns aplicativos de console que se conectam ao MongoDB Atlas e executam operações CRUD básicas.
Obtenha mais informações sobre o driver Ce, para experimentar este código, a maneira mais fácil seria registrar-se para uma conta MongoDB gratuita. Nós mal podemos esperar para ver o que você construirá a seguir!

Ícone do FacebookÍcone do Twitterícone do linkedin
Avalie esse Tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Como criar um sistema RAG com LlamaIndex, OpenAI e MongoDB Vector Database


Feb 16, 2024 | 10 min read
Tutorial

Sincronize seu aplicativo móvel com o MongoDB Atlas e o Google Cloud MySQL


Feb 08, 2024 | 6 min read
Início rápido

Integração do Atlas Search com o BuildSship


Oct 15, 2024 | 4 min read
Tutorial

Melhore Seus Aplicativos de AI : Amazon Web Services Ler mais, MongoDB e Typescript


Oct 10, 2024 | 9 min read
Sumário
  • Introdução ao MongoDB e C