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): CMakeLists.txt.INDENT 0.0
60
61          # Specify the minimum version you require.
62          find_package (mongoc-1.0 1.7 REQUIRED)
63
64          # The "hello_mongoc.c" sample program is shared among four tests.
65          add_executable (hello_mongoc ../../hello_mongoc.c)
66          target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_shared)
67
68
69You  can  also  use libmongoc as a static library instead: Use the mongo::mon‐

goc_static CMake target:

71
72          # Specify the minimum version you require.
73          find_package (mongoc-1.0 1.7 REQUIRED)
74
75          # The "hello_mongoc.c" sample program is shared among four tests.
76          add_executable (hello_mongoc ../../hello_mongoc.c)
77          target_link_libraries (hello_mongoc PRIVATE mongo::mongoc_static)
78
79
80   pkg-config
81       If you're not using CMake, use pkg-config on the command  line  to  set
82       header and library paths:
83
84          gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-1.0)
85
86
87       Or to statically link to libmongoc:
88
89          gcc -o hello_mongoc hello_mongoc.c $(pkg-config --libs --cflags libmongoc-static-1.0)
90
91
92   Specifying header and include paths manually
93       If  you  aren't  using  CMake or pkg-config, paths and libraries can be
94       managed manually.
95
96          $ gcc -o hello_mongoc hello_mongoc.c \
97              -I/usr/local/include/libbson-1.0 -I/usr/local/include/libmongoc-1.0 \
98              -lmongoc-1.0 -lbson-1.0
99          $ ./hello_mongoc
100          { "ok" : 1.000000 }
101
102       For Windows users, the code can be compiled and run with the  following
103       commands. (This assumes that the MongoDB C Driver has been installed to
104       C:\mongo-c-driver; change the include directory as needed.)
105
106          C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 hello_mongoc.c
107          C:\> hello_mongoc
108          { "ok" : 1.000000 }
109

USE LIBMONGOC IN A MICROSOFT VISUAL STUDIO PROJECT

111       See the libmongoc and Visual Studio guide.
112

MAKING A CONNECTION

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

CREATING BSON DOCUMENTS

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

BASIC CRUD OPERATIONS

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

EXECUTING COMMANDS

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

THREADING

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

NEXT STEPS

1028       To find information on advanced topics, browse the rest of the C driver
1029       guide or the official MongoDB documentation.
1030
1031       For  help  with  common  issues,  consult  the Troubleshooting page. To
1032       report a bug or request a new feature, follow these instructions.
1033

AUTHOR

1035       MongoDB, Inc
1036
1038       2017-present, MongoDB, Inc
1039
1040
1041
1042
10431.16.2                           Feb 25, 2020               MONGOC_TUTORIAL(3)
Impressum