1MONGOC_TUTORIAL(3)                 libmongoc                MONGOC_TUTORIAL(3)
2
3
4

NAME

6       mongoc_tutorial - Tutorial
7
8       This guide offers a brief introduction to the MongoDB C Driver.
9
10       For more information on the C API, please refer to the api.
11
12   Contents
13       · Tutorial
14
15         · Installing
16
17         · Starting MongoDB
18
19         · Include and link libmongoc in your C program
20
21         · Use libmongoc in a Microsoft Visual Studio Project
22
23         · Making a Connection
24
25         · Creating BSON Documents
26
27         · Basic CRUD Operations
28
29         · Executing Commands
30
31         · Threading
32
33         · Next Steps
34

INSTALLING

36       For  detailed instructions on installing the MongoDB C Driver on a par‐
37       ticular platform, please see the installation guide.
38

STARTING MONGODB

40       To run the examples in this tutorial, MongoDB  must  be  installed  and
41       running  on  localhost on the default port, 27017. To check if it is up
42       and running, connect to it with the MongoDB shell.
43
44          $ mongo --host localhost --port 27017
45          MongoDB shell version: 3.0.6
46          connecting to: localhost:27017/test
47          >
48
50   Include mongoc.h
51       All libmongoc's functions and types are available in one  header  file.
52       Simply include mongoc/mongoc.h:
53
54          #include <mongoc/mongoc.h>
55
56   CMake
57       The libmongoc installation includes a CMake config-file package, so you
58       can use CMake's find_package command to import libmongoc's CMake target
59       and link to libmongoc (as a shared library):
60
61       CMakeLists.txt
62
63          # Specify the minimum version you require.
64          find_package (mongoc-1.0 1.7 REQUIRED)
65
66          # The "hello_mongoc.c" sample program is shared among four tests.
67          add_executable (hello_mongoc ../../hello_mongoc.c)
68          target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_shared)
69
70
71       You  can  also  use  libmongoc  as  a  static  library instead: Use the
72       mongo::mongoc_static CMake target:
73
74          # Specify the minimum version you require.
75          find_package (mongoc-1.0 1.7 REQUIRED)
76
77          # The "hello_mongoc.c" sample program is shared among four tests.
78          add_executable (hello_mongoc ../../hello_mongoc.c)
79          target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_static)
80
81
82   pkg-config
83       If you're not using CMake, use pkg-config on the command  line  to  set
84       header and library paths:
85
86          gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)
87
88
89       Or to statically link to libmongoc:
90
91          gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)
92
93
94   Specifying header and include paths manually
95       If  you  aren't  using  CMake or pkg-config, paths and libraries can be
96       managed manually.
97
98          $ gcc -o hello_mongoc hello_mongoc.c \
99              -I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
100              -lmongoc-1.0 -lbson-1.0
101          $ ./hello_mongoc
102          { "ok" : 1.000000 }
103
104       For Windows users, the code can be compiled and run with the  following
105       commands. (This assumes that the MongoDB C Driver has been installed to
106       C:\mongo-c-driver; change the include directory as needed.)
107
108          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 hello_mongoc.c
109          C:\> hello_mongoc
110          { "ok" : 1.000000 }
111

USE LIBMONGOC IN A MICROSOFT VISUAL STUDIO PROJECT

113       See the libmongoc and Visual Studio guide.
114

MAKING A CONNECTION

116       Access MongoDB with a mongoc_client_t.  It  transparently  connects  to
117       standalone  servers,  replica  sets  and sharded clusters on demand. To
118       perform operations on a database or collection, create  a  mongoc_data‐
119       base_t or mongoc_collection_t struct from the mongoc_client_t.
120
121       At  the start of an application, call mongoc_init before any other lib‐
122       mongoc functions. At the end, call the appropriate destroy function for
123       each  collection, database, or client handle, in reverse order from how
124       they were constructed. Call mongoc_cleanup before exiting.
125
126       The example below establishes a connection to a  standalone  server  on
127       localhost,  registers  the client application as "connect-example," and
128       performs a simple command.
129
130       More information about database operations can be  found  in  the  CRUD
131       Operations  and  Executing Commands sections. Examples of connecting to
132       replica sets and sharded clusters can be found on the Advanced  Connec‐
133       tions page.
134
135       hello_mongoc.c
136
137          #include <mongoc/mongoc.h>
138
139          int
140          main (int argc, char *argv[])
141          {
142             const char *uri_string = "mongodb://localhost:27017";
143             mongoc_uri_t *uri;
144             mongoc_client_t *client;
145             mongoc_database_t *database;
146             mongoc_collection_t *collection;
147             bson_t *command, reply, *insert;
148             bson_error_t error;
149             char *str;
150             bool retval;
151
152             /*
153              * Required to initialize libmongoc's internals
154              */
155             mongoc_init ();
156
157             /*
158              * Optionally get MongoDB URI from command line
159              */
160             if (argc > 1) {
161                uri_string = argv[1];
162             }
163
164             /*
165              * Safely create a MongoDB URI object from the given string
166              */
167             uri = mongoc_uri_new_with_error (uri_string, &error);
168             if (!uri) {
169                fprintf (stderr,
170                         "failed to parse URI: %s\n"
171                         "error message:       %s\n",
172                         uri_string,
173                         error.message);
174                return EXIT_FAILURE;
175             }
176
177             /*
178              * Create a new client instance
179              */
180             client = mongoc_client_new_from_uri (uri);
181             if (!client) {
182                return EXIT_FAILURE;
183             }
184
185             /*
186              * Register the application name so we can track it in the profile logs
187              * on the server. This can also be done from the URI (see other examples).
188              */
189             mongoc_client_set_appname (client, "connect-example");
190
191             /*
192              * Get a handle on the database "db_name" and collection "coll_name"
193              */
194             database = mongoc_client_get_database (client, "db_name");
195             collection = mongoc_client_get_collection (client, "db_name", "coll_name");
196
197             /*
198              * Do work. This example pings the database, prints the result as JSON and
199              * performs an insert
200              */
201             command = BCON_NEW ("ping", BCON_INT32 (1));
202
203             retval = mongoc_client_command_simple (
204                client, "admin", command, NULL, &reply, &error);
205
206             if (!retval) {
207                fprintf (stderr, "%s\n", error.message);
208                return EXIT_FAILURE;
209             }
210
211             str = bson_as_json (&reply, NULL);
212             printf ("%s\n", str);
213
214             insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
215
216             if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) {
217                fprintf (stderr, "%s\n", error.message);
218             }
219
220             bson_destroy (insert);
221             bson_destroy (&reply);
222             bson_destroy (command);
223             bson_free (str);
224
225             /*
226              * Release our handles and clean up libmongoc
227              */
228             mongoc_collection_destroy (collection);
229             mongoc_database_destroy (database);
230             mongoc_uri_destroy (uri);
231             mongoc_client_destroy (client);
232             mongoc_cleanup ();
233
234             return EXIT_SUCCESS;
235          }
236
237

CREATING BSON DOCUMENTS

239       Documents  are stored in MongoDB's data format, BSON. The C driver uses
240       libbson to create BSON documents. There are several ways  to  construct
241       them: appending key-value pairs, using BCON, or parsing JSON.
242
243   Appending BSON
244       A  BSON  document,  represented as a bson_t in code, can be constructed
245       one field at a time using libbson's append functions.
246
247       For example, to create a document like this:
248
249          {
250             born : ISODate("1906-12-09"),
251             died : ISODate("1992-01-01"),
252             name : {
253                first : "Grace",
254                last : "Hopper"
255             },
256             languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
257             degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
258          }
259
260       Use the following code:
261
262          #include <bson/bson.h>
263
264          int
265          main (int   argc,
266                char *argv[])
267          {
268             struct tm   born = { 0 };
269             struct tm   died = { 0 };
270             const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
271             const char *schools[] = {"Vassar", "Yale"};
272             const char *degrees[] = {"BA", "PhD"};
273             uint32_t    i;
274             char        buf[16];
275             const       char *key;
276             size_t      keylen;
277             bson_t     *document;
278             bson_t      child;
279             bson_t      child2;
280             char       *str;
281
282             document = bson_new ();
283
284             /*
285              * Append { "born" : ISODate("1906-12-09") } to the document.
286              * Passing -1 for the length argument tells libbson to calculate the string length.
287              */
288             born.tm_year = 6;  /* years are 1900-based */
289             born.tm_mon = 11;  /* months are 0-based */
290             born.tm_mday = 9;
291             bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
292
293             /*
294              * Append { "died" : ISODate("1992-01-01") } to the document.
295              */
296             died.tm_year = 92;
297             died.tm_mon = 0;
298             died.tm_mday = 1;
299
300             /*
301              * For convenience, this macro passes length -1 by default.
302              */
303             BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
304
305             /*
306              * Append a subdocument.
307              */
308             BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
309             BSON_APPEND_UTF8 (&child, "first", "Grace");
310             BSON_APPEND_UTF8 (&child, "last", "Hopper");
311             bson_append_document_end (document, &child);
312
313             /*
314              * Append array of strings. Generate keys "0", "1", "2".
315              */
316             BSON_APPEND_ARRAY_BEGIN (document, "languages", &child);
317             for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
318                keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
319                bson_append_utf8 (&child, key, (int) keylen, lang_names[i], -1);
320             }
321             bson_append_array_end (document, &child);
322
323             /*
324              * Array of subdocuments:
325              *    degrees: [ { degree: "BA", school: "Vassar" }, ... ]
326              */
327             BSON_APPEND_ARRAY_BEGIN (document, "degrees", &child);
328             for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
329                keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
330                bson_append_document_begin (&child, key, (int) keylen, &child2);
331                BSON_APPEND_UTF8 (&child2, "degree", degrees[i]);
332                BSON_APPEND_UTF8 (&child2, "school", schools[i]);
333                bson_append_document_end (&child, &child2);
334             }
335             bson_append_array_end (document, &child);
336
337             /*
338              * Print the document as a JSON string.
339              */
340             str = bson_as_canonical_extended_json (document, NULL);
341             printf ("%s\n", str);
342             bson_free (str);
343
344             /*
345              * Clean up allocated bson documents.
346              */
347             bson_destroy (document);
348             return 0;
349          }
350
351       See the libbson documentation for all of the types that can be appended
352       to a bson_t.
353
354   Using BCON
355       BSON  C  Object Notation, BCON for short, is an alternative way of con‐
356       structing BSON documents in a manner closer to the intended format.  It
357       has  less  type-safety than BSON's append functions but results in less
358       code.
359
360          #include <bson/bson.h>
361
362          int
363          main (int   argc,
364                char *argv[])
365          {
366             struct tm born = { 0 };
367             struct tm died = { 0 };
368             bson_t   *document;
369             char     *str;
370
371             born.tm_year = 6;
372             born.tm_mon = 11;
373             born.tm_mday = 9;
374
375             died.tm_year = 92;
376             died.tm_mon = 0;
377             died.tm_mday = 1;
378
379             document = BCON_NEW (
380                "born", BCON_DATE_TIME (mktime (&born) * 1000),
381                "died", BCON_DATE_TIME (mktime (&died) * 1000),
382                "name", "{",
383                "first", BCON_UTF8 ("Grace"),
384                "last", BCON_UTF8 ("Hopper"),
385                "}",
386                "languages", "[",
387                BCON_UTF8 ("MATH-MATIC"),
388                BCON_UTF8 ("FLOW-MATIC"),
389                BCON_UTF8 ("COBOL"),
390                "]",
391                "degrees", "[",
392                "{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
393                "{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
394                "]");
395
396             /*
397              * Print the document as a JSON string.
398              */
399             str = bson_as_canonical_extended_json (document, NULL);
400             printf ("%s\n", str);
401             bson_free (str);
402
403             /*
404              * Clean up allocated bson documents.
405              */
406             bson_destroy (document);
407             return 0;
408          }
409
410       Notice that BCON can create arrays, subdocuments and arbitrary fields.
411
412   Creating BSON from JSON
413       For single documents,  BSON  can  be  created  from  JSON  strings  via
414       bson_new_from_json.
415
416          #include <bson/bson.h>
417
418          int
419          main (int   argc,
420                char *argv[])
421          {
422             bson_error_t error;
423             bson_t      *bson;
424             char        *string;
425
426             const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
427             bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
428
429             if (!bson) {
430                fprintf (stderr, "%s\n", error.message);
431                return EXIT_FAILURE;
432             }
433
434             string = bson_as_canonical_extended_json (bson, NULL);
435             printf ("%s\n", string);
436             bson_free (string);
437
438             return 0;
439          }
440
441       To   initialize   BSON   from   a   sequence  of  JSON  documents,  use
442       bson_json_reader_t.
443

BASIC CRUD OPERATIONS

445       This section demonstrates the basics of using the C Driver to  interact
446       with MongoDB.
447
448   Inserting a Document
449       To  insert documents into a collection, first obtain a handle to a mon‐
450       goc_collection_t  via  a  mongoc_client_t.  Then,  use   mongoc_collec‐
451       tion_insert_one  to  add BSON documents to the collection. This example
452       inserts into the database "mydb" and collection "mycoll".
453
454       When finished, ensure that allocated  structures  are  freed  by  using
455       their respective destroy functions.
456
457          #include <bson/bson.h>
458          #include <mongoc/mongoc.h>
459          #include <stdio.h>
460
461          int
462          main (int   argc,
463                char *argv[])
464          {
465              mongoc_client_t *client;
466              mongoc_collection_t *collection;
467              bson_error_t error;
468              bson_oid_t oid;
469              bson_t *doc;
470
471              mongoc_init ();
472
473              client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
474              collection = mongoc_client_get_collection (client, "mydb", "mycoll");
475
476              doc = bson_new ();
477              bson_oid_init (&oid, NULL);
478              BSON_APPEND_OID (doc, "_id", &oid);
479              BSON_APPEND_UTF8 (doc, "hello", "world");
480
481              if (!mongoc_collection_insert_one (
482                     collection, doc, NULL, NULL, &error)) {
483                  fprintf (stderr, "%s\n", error.message);
484              }
485
486              bson_destroy (doc);
487              mongoc_collection_destroy (collection);
488              mongoc_client_destroy (client);
489              mongoc_cleanup ();
490
491              return 0;
492          }
493
494       Compile the code and run it:
495
496          $ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
497          $ ./insert
498
499       On Windows:
500
501          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
502          C:\> insert
503
504       To verify that the insert succeeded, connect with the MongoDB shell.
505
506          $ mongo
507          MongoDB shell version: 3.0.6
508          connecting to: test
509          > use mydb
510          switched to db mydb
511          > db.mycoll.find()
512          { "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
513          >
514
515   Finding a Document
516       To  query a MongoDB collection with the C driver, use the function mon‐
517       goc_collection_find_with_opts(). This returns a cursor to the  matching
518       documents.  The  following  examples iterate through the result cursors
519       and print the matches to stdout as JSON strings.
520
521       Use a document as a query specifier; for example,
522
523          { "color" : "red" }
524
525       will match any document with a field named "color" with value "red". An
526       empty document {} can be used to match all documents.
527
528       This  first example uses an empty query specifier to find all documents
529       in the database "mydb" and collection "mycoll".
530
531          #include <bson/bson.h>
532          #include <mongoc/mongoc.h>
533          #include <stdio.h>
534
535          int
536          main (int argc, char *argv[])
537          {
538             mongoc_client_t *client;
539             mongoc_collection_t *collection;
540             mongoc_cursor_t *cursor;
541             const bson_t *doc;
542             bson_t *query;
543             char *str;
544
545             mongoc_init ();
546
547             client =
548                mongoc_client_new ("mongodb://localhost:27017/?appname=find-example");
549             collection = mongoc_client_get_collection (client, "mydb", "mycoll");
550             query = bson_new ();
551             cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
552
553             while (mongoc_cursor_next (cursor, &doc)) {
554                str = bson_as_canonical_extended_json (doc, NULL);
555                printf ("%s\n", str);
556                bson_free (str);
557             }
558
559             bson_destroy (query);
560             mongoc_cursor_destroy (cursor);
561             mongoc_collection_destroy (collection);
562             mongoc_client_destroy (client);
563             mongoc_cleanup ();
564
565             return 0;
566          }
567
568       Compile the code and run it:
569
570          $ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
571          $ ./find
572          { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
573
574       On Windows:
575
576          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
577          C:\> find
578          { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
579
580       To look for a specific document, add a specifier to query. This example
581       adds  a  call  to BSON_APPEND_UTF8() to look for all documents matching
582       {"hello" : "world"}.
583
584          #include <bson/bson.h>
585          #include <mongoc/mongoc.h>
586          #include <stdio.h>
587
588          int
589          main (int argc, char *argv[])
590          {
591             mongoc_client_t *client;
592             mongoc_collection_t *collection;
593             mongoc_cursor_t *cursor;
594             const bson_t *doc;
595             bson_t *query;
596             char *str;
597
598             mongoc_init ();
599
600             client = mongoc_client_new (
601                "mongodb://localhost:27017/?appname=find-specific-example");
602             collection = mongoc_client_get_collection (client, "mydb", "mycoll");
603             query = bson_new ();
604             BSON_APPEND_UTF8 (query, "hello", "world");
605
606             cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
607
608             while (mongoc_cursor_next (cursor, &doc)) {
609                str = bson_as_canonical_extended_json (doc, NULL);
610                printf ("%s\n", str);
611                bson_free (str);
612             }
613
614             bson_destroy (query);
615             mongoc_cursor_destroy (cursor);
616             mongoc_collection_destroy (collection);
617             mongoc_client_destroy (client);
618             mongoc_cleanup ();
619
620             return 0;
621          }
622
623          $ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
624          $ ./find-specific
625          { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
626
627          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
628          C:\> find-specific
629          { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
630
631   Updating a Document
632       This  code  snippet  gives   an   example   of   using   mongoc_collec‐
633       tion_update_one() to update the fields of a document.
634
635       Using  the  "mydb"  database,  the following example inserts an example
636       document into the "mycoll" collection. Then, using its _id  field,  the
637       document is updated with different values and a new field.
638
639          #include <bson/bson.h>
640          #include <mongoc/mongoc.h>
641          #include <stdio.h>
642
643          int
644          main (int argc, char *argv[])
645          {
646             mongoc_collection_t *collection;
647             mongoc_client_t *client;
648             bson_error_t error;
649             bson_oid_t oid;
650             bson_t *doc = NULL;
651             bson_t *update = NULL;
652             bson_t *query = NULL;
653
654             mongoc_init ();
655
656             client =
657                mongoc_client_new ("mongodb://localhost:27017/?appname=update-example");
658             collection = mongoc_client_get_collection (client, "mydb", "mycoll");
659
660             bson_oid_init (&oid, NULL);
661             doc = BCON_NEW ("_id", BCON_OID (&oid), "key", BCON_UTF8 ("old_value"));
662
663             if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
664                fprintf (stderr, "%s\n", error.message);
665                goto fail;
666             }
667
668             query = BCON_NEW ("_id", BCON_OID (&oid));
669             update = BCON_NEW ("$set",
670                                "{",
671                                "key",
672                                BCON_UTF8 ("new_value"),
673                                "updated",
674                                BCON_BOOL (true),
675                                "}");
676
677             if (!mongoc_collection_update_one (
678                    collection, query, update, NULL, NULL, &error)) {
679                fprintf (stderr, "%s\n", error.message);
680                goto fail;
681             }
682
683          fail:
684             if (doc)
685                bson_destroy (doc);
686             if (query)
687                bson_destroy (query);
688             if (update)
689                bson_destroy (update);
690
691             mongoc_collection_destroy (collection);
692             mongoc_client_destroy (client);
693             mongoc_cleanup ();
694
695             return 0;
696          }
697
698       Compile the code and run it:
699
700          $ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
701          $ ./update
702
703       On Windows:
704
705          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
706          C:\> update
707          { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
708
709       To verify that the update succeeded, connect with the MongoDB shell.
710
711          $ mongo
712          MongoDB shell version: 3.0.6
713          connecting to: test
714          > use mydb
715          switched to db mydb
716          > db.mycoll.find({"updated" : true})
717          { "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
718          >
719
720   Deleting a Document
721       This  example  illustrates the use of mongoc_collection_delete_one() to
722       delete a document.
723
724       The following code inserts a sample document into the  database  "mydb"
725       and  collection  "mycoll".  Then,  it  deletes  all  documents matching
726       {"hello" : "world"}.
727
728          #include <bson/bson.h>
729          #include <mongoc/mongoc.h>
730          #include <stdio.h>
731
732          int
733          main (int argc, char *argv[])
734          {
735             mongoc_client_t *client;
736             mongoc_collection_t *collection;
737             bson_error_t error;
738             bson_oid_t oid;
739             bson_t *doc;
740
741             mongoc_init ();
742
743             client =
744                mongoc_client_new ("mongodb://localhost:27017/?appname=delete-example");
745             collection = mongoc_client_get_collection (client, "test", "test");
746
747             doc = bson_new ();
748             bson_oid_init (&oid, NULL);
749             BSON_APPEND_OID (doc, "_id", &oid);
750             BSON_APPEND_UTF8 (doc, "hello", "world");
751
752             if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
753                fprintf (stderr, "Insert failed: %s\n", error.message);
754             }
755
756             bson_destroy (doc);
757
758             doc = bson_new ();
759             BSON_APPEND_OID (doc, "_id", &oid);
760
761             if (!mongoc_collection_delete_one (
762                    collection, doc, NULL, NULL, &error)) {
763                fprintf (stderr, "Delete failed: %s\n", error.message);
764             }
765
766             bson_destroy (doc);
767             mongoc_collection_destroy (collection);
768             mongoc_client_destroy (client);
769             mongoc_cleanup ();
770
771             return 0;
772          }
773
774       Compile the code and run it:
775
776          $ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
777          $ ./delete
778
779       On Windows:
780
781          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
782          C:\> delete
783
784       Use the MongoDB shell to prove that the  documents  have  been  removed
785       successfully.
786
787          $ mongo
788          MongoDB shell version: 3.0.6
789          connecting to: test
790          > use mydb
791          switched to db mydb
792          > db.mycoll.count({"hello" : "world"})
793          0
794          >
795
796   Counting Documents
797       Counting  the number of documents in a MongoDB collection is similar to
798       performing a find operation. This example counts the  number  of  docu‐
799       ments  matching  {"hello" : "world"} in the database "mydb" and collec‐
800       tion "mycoll".
801
802          #include <bson/bson.h>
803          #include <mongoc/mongoc.h>
804          #include <stdio.h>
805
806          int
807          main (int argc, char *argv[])
808          {
809             mongoc_client_t *client;
810             mongoc_collection_t *collection;
811             bson_error_t error;
812             bson_t *doc;
813             int64_t count;
814
815             mongoc_init ();
816
817             client =
818                mongoc_client_new ("mongodb://localhost:27017/?appname=count-example");
819             collection = mongoc_client_get_collection (client, "mydb", "mycoll");
820             doc = bson_new_from_json (
821                (const uint8_t *) "{\"hello\" : \"world\"}", -1, &error);
822
823             count = mongoc_collection_count (
824                collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
825
826             if (count < 0) {
827                fprintf (stderr, "%s\n", error.message);
828             } else {
829                printf ("%" PRId64 "\n", count);
830             }
831
832             bson_destroy (doc);
833             mongoc_collection_destroy (collection);
834             mongoc_client_destroy (client);
835             mongoc_cleanup ();
836
837             return 0;
838          }
839
840       Compile the code and run it:
841
842          $ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
843          $ ./count
844          1
845
846       On Windows:
847
848          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
849          C:\> count
850          1
851

EXECUTING COMMANDS

853       The driver provides helper functions for executing MongoDB commands  on
854       client, database and collection structures. These functions return cur‐
855       sors; the _simple variants return booleans indicating success or  fail‐
856       ure.
857
858       This  example  executes  the  collStats  command against the collection
859       "mycoll" in database "mydb".
860
861          #include <bson/bson.h>
862          #include <mongoc/mongoc.h>
863          #include <stdio.h>
864
865          int
866          main (int argc, char *argv[])
867          {
868             mongoc_client_t *client;
869             mongoc_collection_t *collection;
870             bson_error_t error;
871             bson_t *command;
872             bson_t reply;
873             char *str;
874
875             mongoc_init ();
876
877             client = mongoc_client_new (
878                "mongodb://localhost:27017/?appname=executing-example");
879             collection = mongoc_client_get_collection (client, "mydb", "mycoll");
880
881             command = BCON_NEW ("collStats", BCON_UTF8 ("mycoll"));
882             if (mongoc_collection_command_simple (
883                    collection, command, NULL, &reply, &error)) {
884                str = bson_as_canonical_extended_json (&reply, NULL);
885                printf ("%s\n", str);
886                bson_free (str);
887             } else {
888                fprintf (stderr, "Failed to run command: %s\n", error.message);
889             }
890
891             bson_destroy (command);
892             bson_destroy (&reply);
893             mongoc_collection_destroy (collection);
894             mongoc_client_destroy (client);
895             mongoc_cleanup ();
896
897             return 0;
898          }
899
900       Compile the code and run it:
901
902          $ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
903          $ ./executing
904          { "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
905          "lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
906          "indexDetails" : {  }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
907
908       On Windows:
909
910          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
911          C:\> executing
912          { "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
913          "lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
914          "indexDetails" : {  }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
915

THREADING

917       The MongoDB C Driver is thread-unaware in  the  vast  majority  of  its
918       operations.  This  means  it  is  up  to  the  programmer  to guarantee
919       thread-safety.
920
921       However, mongoc_client_pool_t is thread-safe and is  used  to  fetch  a
922       mongoc_client_t in a thread-safe manner. After retrieving a client from
923       the pool, the client structure should be considered owned by the  call‐
924       ing  thread.  When  the thread is finished, the client should be placed
925       back into the pool.
926
927       example-pool.c
928
929          /* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
930           * libmongoc-1.0) */
931
932          /* ./example-pool [CONNECTION_STRING] */
933
934          #include <mongoc/mongoc.h>
935          #include <pthread.h>
936          #include <stdio.h>
937
938          static pthread_mutex_t mutex;
939          static bool in_shutdown = false;
940
941          static void *
942          worker (void *data)
943          {
944             mongoc_client_pool_t *pool = data;
945             mongoc_client_t *client;
946             bson_t ping = BSON_INITIALIZER;
947             bson_error_t error;
948             bool r;
949
950             BSON_APPEND_INT32 (&ping, "ping", 1);
951
952             while (true) {
953                client = mongoc_client_pool_pop (pool);
954                /* Do something with client. If you are writing an HTTP server, you
955                 * probably only want to hold onto the client for the portion of the
956                 * request performing database queries.
957                 */
958                r = mongoc_client_command_simple (
959                   client, "admin", &ping, NULL, NULL, &error);
960
961                if (!r) {
962                   fprintf (stderr, "%s\n", error.message);
963                }
964
965                mongoc_client_pool_push (pool, client);
966
967                pthread_mutex_lock (&mutex);
968                if (in_shutdown || !r) {
969                   pthread_mutex_unlock (&mutex);
970                   break;
971                }
972
973                pthread_mutex_unlock (&mutex);
974             }
975
976             bson_destroy (&ping);
977             return NULL;
978          }
979
980          int
981          main (int argc, char *argv[])
982          {
983             const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
984             mongoc_uri_t *uri;
985             bson_error_t error;
986             mongoc_client_pool_t *pool;
987             pthread_t threads[10];
988             unsigned i;
989             void *ret;
990
991             pthread_mutex_init (&mutex, NULL);
992             mongoc_init ();
993
994             if (argc > 1) {
995                uri_string = argv[1];
996             }
997
998             uri = mongoc_uri_new_with_error (uri_string, &error);
999             if (!uri) {
1000                fprintf (stderr,
1001                         "failed to parse URI: %s\n"
1002                         "error message:       %s\n",
1003                         uri_string,
1004                         error.message);
1005                return EXIT_FAILURE;
1006             }
1007
1008             pool = mongoc_client_pool_new (uri);
1009             mongoc_client_pool_set_error_api (pool, 2);
1010
1011             for (i = 0; i < 10; i++) {
1012                pthread_create (&threads[i], NULL, worker, pool);
1013             }
1014
1015             sleep (10);
1016             pthread_mutex_lock (&mutex);
1017             in_shutdown = true;
1018             pthread_mutex_unlock (&mutex);
1019
1020             for (i = 0; i < 10; i++) {
1021                pthread_join (threads[i], &ret);
1022             }
1023
1024             mongoc_client_pool_destroy (pool);
1025             mongoc_uri_destroy (uri);
1026
1027             mongoc_cleanup ();
1028
1029             return EXIT_SUCCESS;
1030          }
1031
1032

NEXT STEPS

1034       To find information on advanced topics, browse the rest of the C driver
1035       guide or the official MongoDB documentation.
1036
1037       For  help  with  common  issues,  consult  the Troubleshooting page. To
1038       report a bug or request a new feature, follow these instructions.
1039

AUTHOR

1041       MongoDB, Inc
1042
1044       2017-present, MongoDB, Inc
1045
1046
1047
1048
10491.17.4                           Feb 04, 2021               MONGOC_TUTORIAL(3)
Impressum