1MONGOC_TUTORIAL(3) libmongoc MONGOC_TUTORIAL(3)
2
3
4
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 Reference.
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
36 For detailed instructions on installing the MongoDB C Driver on a par‐
37 ticular platform, please see the installation guide.
38
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
113 See the libmongoc and Visual Studio guide.
114
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
119 mongoc_database_t or mongoc_collection_t struct from the
120 mongoc_client_t.
121
122 At the start of an application, call mongoc_init() before any other
123 libmongoc functions. At the end, call the appropriate destroy function
124 for each collection, database, or client handle, in reverse order from
125 how they were constructed. Call mongoc_cleanup() before exiting.
126
127 The example below establishes a connection to a standalone server on
128 localhost, registers the client application as "connect-example," and
129 performs a simple command.
130
131 More information about database operations can be found in the CRUD Op‐
132 erations and Executing Commands sections. Examples of connecting to
133 replica sets and sharded clusters can be found on the Advanced Connec‐
134 tions page.
135
136 hello_mongoc.c
137
138 #include <mongoc/mongoc.h>
139
140 int
141 main (int argc, char *argv[])
142 {
143 const char *uri_string = "mongodb://localhost:27017";
144 mongoc_uri_t *uri;
145 mongoc_client_t *client;
146 mongoc_database_t *database;
147 mongoc_collection_t *collection;
148 bson_t *command, reply, *insert;
149 bson_error_t error;
150 char *str;
151 bool retval;
152
153 /*
154 * Required to initialize libmongoc's internals
155 */
156 mongoc_init ();
157
158 /*
159 * Optionally get MongoDB URI from command line
160 */
161 if (argc > 1) {
162 uri_string = argv[1];
163 }
164
165 /*
166 * Safely create a MongoDB URI object from the given string
167 */
168 uri = mongoc_uri_new_with_error (uri_string, &error);
169 if (!uri) {
170 fprintf (stderr,
171 "failed to parse URI: %s\n"
172 "error message: %s\n",
173 uri_string,
174 error.message);
175 return EXIT_FAILURE;
176 }
177
178 /*
179 * Create a new client instance
180 */
181 client = mongoc_client_new_from_uri (uri);
182 if (!client) {
183 return EXIT_FAILURE;
184 }
185
186 /*
187 * Register the application name so we can track it in the profile logs
188 * on the server. This can also be done from the URI (see other examples).
189 */
190 mongoc_client_set_appname (client, "connect-example");
191
192 /*
193 * Get a handle on the database "db_name" and collection "coll_name"
194 */
195 database = mongoc_client_get_database (client, "db_name");
196 collection = mongoc_client_get_collection (client, "db_name", "coll_name");
197
198 /*
199 * Do work. This example pings the database, prints the result as JSON and
200 * performs an insert
201 */
202 command = BCON_NEW ("ping", BCON_INT32 (1));
203
204 retval = mongoc_client_command_simple (
205 client, "admin", command, NULL, &reply, &error);
206
207 if (!retval) {
208 fprintf (stderr, "%s\n", error.message);
209 return EXIT_FAILURE;
210 }
211
212 str = bson_as_json (&reply, NULL);
213 printf ("%s\n", str);
214
215 insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
216
217 if (!mongoc_collection_insert_one (collection, insert, NULL, NULL, &error)) {
218 fprintf (stderr, "%s\n", error.message);
219 }
220
221 bson_destroy (insert);
222 bson_destroy (&reply);
223 bson_destroy (command);
224 bson_free (str);
225
226 /*
227 * Release our handles and clean up libmongoc
228 */
229 mongoc_collection_destroy (collection);
230 mongoc_database_destroy (database);
231 mongoc_uri_destroy (uri);
232 mongoc_client_destroy (client);
233 mongoc_cleanup ();
234
235 return EXIT_SUCCESS;
236 }
237
238
240 Documents are stored in MongoDB's data format, BSON. The C driver uses
241 libbson to create BSON documents. There are several ways to construct
242 them: appending key-value pairs, using BCON, or parsing JSON.
243
244 Appending BSON
245 A BSON document, represented as a bson_t in code, can be constructed
246 one field at a time using libbson's append functions.
247
248 For example, to create a document like this:
249
250 {
251 born : ISODate("1906-12-09"),
252 died : ISODate("1992-01-01"),
253 name : {
254 first : "Grace",
255 last : "Hopper"
256 },
257 languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
258 degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
259 }
260
261 Use the following code:
262
263 #include <bson/bson.h>
264
265 int
266 main (int argc,
267 char *argv[])
268 {
269 struct tm born = { 0 };
270 struct tm died = { 0 };
271 const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
272 const char *schools[] = {"Vassar", "Yale"};
273 const char *degrees[] = {"BA", "PhD"};
274 uint32_t i;
275 char buf[16];
276 const char *key;
277 size_t keylen;
278 bson_t *document;
279 bson_t child;
280 bson_t child2;
281 char *str;
282
283 document = bson_new ();
284
285 /*
286 * Append { "born" : ISODate("1906-12-09") } to the document.
287 * Passing -1 for the length argument tells libbson to calculate the string length.
288 */
289 born.tm_year = 6; /* years are 1900-based */
290 born.tm_mon = 11; /* months are 0-based */
291 born.tm_mday = 9;
292 bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
293
294 /*
295 * Append { "died" : ISODate("1992-01-01") } to the document.
296 */
297 died.tm_year = 92;
298 died.tm_mon = 0;
299 died.tm_mday = 1;
300
301 /*
302 * For convenience, this macro passes length -1 by default.
303 */
304 BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
305
306 /*
307 * Append a subdocument.
308 */
309 BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
310 BSON_APPEND_UTF8 (&child, "first", "Grace");
311 BSON_APPEND_UTF8 (&child, "last", "Hopper");
312 bson_append_document_end (document, &child);
313
314 /*
315 * Append array of strings. Generate keys "0", "1", "2".
316 */
317 BSON_APPEND_ARRAY_BEGIN (document, "languages", &child);
318 for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
319 keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
320 bson_append_utf8 (&child, key, (int) keylen, lang_names[i], -1);
321 }
322 bson_append_array_end (document, &child);
323
324 /*
325 * Array of subdocuments:
326 * degrees: [ { degree: "BA", school: "Vassar" }, ... ]
327 */
328 BSON_APPEND_ARRAY_BEGIN (document, "degrees", &child);
329 for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
330 keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
331 bson_append_document_begin (&child, key, (int) keylen, &child2);
332 BSON_APPEND_UTF8 (&child2, "degree", degrees[i]);
333 BSON_APPEND_UTF8 (&child2, "school", schools[i]);
334 bson_append_document_end (&child, &child2);
335 }
336 bson_append_array_end (document, &child);
337
338 /*
339 * Print the document as a JSON string.
340 */
341 str = bson_as_canonical_extended_json (document, NULL);
342 printf ("%s\n", str);
343 bson_free (str);
344
345 /*
346 * Clean up allocated bson documents.
347 */
348 bson_destroy (document);
349 return 0;
350 }
351
352 See the libbson documentation for all of the types that can be appended
353 to a bson_t.
354
355 Using BCON
356 BSON C Object Notation, BCON for short, is an alternative way of con‐
357 structing BSON documents in a manner closer to the intended format. It
358 has less type-safety than BSON's append functions but results in less
359 code.
360
361 #include <bson/bson.h>
362
363 int
364 main (int argc,
365 char *argv[])
366 {
367 struct tm born = { 0 };
368 struct tm died = { 0 };
369 bson_t *document;
370 char *str;
371
372 born.tm_year = 6;
373 born.tm_mon = 11;
374 born.tm_mday = 9;
375
376 died.tm_year = 92;
377 died.tm_mon = 0;
378 died.tm_mday = 1;
379
380 document = BCON_NEW (
381 "born", BCON_DATE_TIME (mktime (&born) * 1000),
382 "died", BCON_DATE_TIME (mktime (&died) * 1000),
383 "name", "{",
384 "first", BCON_UTF8 ("Grace"),
385 "last", BCON_UTF8 ("Hopper"),
386 "}",
387 "languages", "[",
388 BCON_UTF8 ("MATH-MATIC"),
389 BCON_UTF8 ("FLOW-MATIC"),
390 BCON_UTF8 ("COBOL"),
391 "]",
392 "degrees", "[",
393 "{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
394 "{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
395 "]");
396
397 /*
398 * Print the document as a JSON string.
399 */
400 str = bson_as_canonical_extended_json (document, NULL);
401 printf ("%s\n", str);
402 bson_free (str);
403
404 /*
405 * Clean up allocated bson documents.
406 */
407 bson_destroy (document);
408 return 0;
409 }
410
411 Notice that BCON can create arrays, subdocuments and arbitrary fields.
412
413 Creating BSON from JSON
414 For single documents, BSON can be created from JSON strings via
415 bson_new_from_json.
416
417 #include <bson/bson.h>
418
419 int
420 main (int argc,
421 char *argv[])
422 {
423 bson_error_t error;
424 bson_t *bson;
425 char *string;
426
427 const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
428 bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
429
430 if (!bson) {
431 fprintf (stderr, "%s\n", error.message);
432 return EXIT_FAILURE;
433 }
434
435 string = bson_as_canonical_extended_json (bson, NULL);
436 printf ("%s\n", string);
437 bson_free (string);
438
439 return 0;
440 }
441
442 To initialize BSON from a sequence of JSON documents, use
443 bson_json_reader_t.
444
446 This section demonstrates the basics of using the C Driver to interact
447 with MongoDB.
448
449 Inserting a Document
450 To insert documents into a collection, first obtain a handle to a mon‐
451 goc_collection_t via a mongoc_client_t. Then, use
452 mongoc_collection_insert_one() to add BSON documents to the collection.
453 This example inserts into the database "mydb" and collection "mycoll".
454
455 When finished, ensure that allocated structures are freed by using
456 their respective destroy functions.
457
458 #include <bson/bson.h>
459 #include <mongoc/mongoc.h>
460 #include <stdio.h>
461
462 int
463 main (int argc,
464 char *argv[])
465 {
466 mongoc_client_t *client;
467 mongoc_collection_t *collection;
468 bson_error_t error;
469 bson_oid_t oid;
470 bson_t *doc;
471
472 mongoc_init ();
473
474 client = mongoc_client_new ("mongodb://localhost:27017/?appname=insert-example");
475 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
476
477 doc = bson_new ();
478 bson_oid_init (&oid, NULL);
479 BSON_APPEND_OID (doc, "_id", &oid);
480 BSON_APPEND_UTF8 (doc, "hello", "world");
481
482 if (!mongoc_collection_insert_one (
483 collection, doc, NULL, NULL, &error)) {
484 fprintf (stderr, "%s\n", error.message);
485 }
486
487 bson_destroy (doc);
488 mongoc_collection_destroy (collection);
489 mongoc_client_destroy (client);
490 mongoc_cleanup ();
491
492 return 0;
493 }
494
495 Compile the code and run it:
496
497 $ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
498 $ ./insert
499
500 On Windows:
501
502 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
503 C:\> insert
504
505 To verify that the insert succeeded, connect with the MongoDB shell.
506
507 $ mongo
508 MongoDB shell version: 3.0.6
509 connecting to: test
510 > use mydb
511 switched to db mydb
512 > db.mycoll.find()
513 { "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
514 >
515
516 Finding a Document
517 To query a MongoDB collection with the C driver, use the function
518 mongoc_collection_find_with_opts(). This returns a cursor to the match‐
519 ing documents. The following examples iterate through the result cur‐
520 sors and print the matches to stdout as JSON strings.
521
522 Use a document as a query specifier; for example,
523
524 { "color" : "red" }
525
526 will match any document with a field named "color" with value "red". An
527 empty document {} can be used to match all documents.
528
529 This first example uses an empty query specifier to find all documents
530 in the database "mydb" and collection "mycoll".
531
532 #include <bson/bson.h>
533 #include <mongoc/mongoc.h>
534 #include <stdio.h>
535
536 int
537 main (int argc, char *argv[])
538 {
539 mongoc_client_t *client;
540 mongoc_collection_t *collection;
541 mongoc_cursor_t *cursor;
542 const bson_t *doc;
543 bson_t *query;
544 char *str;
545
546 mongoc_init ();
547
548 client =
549 mongoc_client_new ("mongodb://localhost:27017/?appname=find-example");
550 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
551 query = bson_new ();
552 cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
553
554 while (mongoc_cursor_next (cursor, &doc)) {
555 str = bson_as_canonical_extended_json (doc, NULL);
556 printf ("%s\n", str);
557 bson_free (str);
558 }
559
560 bson_destroy (query);
561 mongoc_cursor_destroy (cursor);
562 mongoc_collection_destroy (collection);
563 mongoc_client_destroy (client);
564 mongoc_cleanup ();
565
566 return 0;
567 }
568
569 Compile the code and run it:
570
571 $ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
572 $ ./find
573 { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
574
575 On Windows:
576
577 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
578 C:\> find
579 { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
580
581 To look for a specific document, add a specifier to query. This example
582 adds a call to BSON_APPEND_UTF8() to look for all documents matching
583 {"hello" : "world"}.
584
585 #include <bson/bson.h>
586 #include <mongoc/mongoc.h>
587 #include <stdio.h>
588
589 int
590 main (int argc, char *argv[])
591 {
592 mongoc_client_t *client;
593 mongoc_collection_t *collection;
594 mongoc_cursor_t *cursor;
595 const bson_t *doc;
596 bson_t *query;
597 char *str;
598
599 mongoc_init ();
600
601 client = mongoc_client_new (
602 "mongodb://localhost:27017/?appname=find-specific-example");
603 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
604 query = bson_new ();
605 BSON_APPEND_UTF8 (query, "hello", "world");
606
607 cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);
608
609 while (mongoc_cursor_next (cursor, &doc)) {
610 str = bson_as_canonical_extended_json (doc, NULL);
611 printf ("%s\n", str);
612 bson_free (str);
613 }
614
615 bson_destroy (query);
616 mongoc_cursor_destroy (cursor);
617 mongoc_collection_destroy (collection);
618 mongoc_client_destroy (client);
619 mongoc_cleanup ();
620
621 return 0;
622 }
623
624 $ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
625 $ ./find-specific
626 { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
627
628 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
629 C:\> find-specific
630 { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
631
632 Updating a Document
633 This code snippet gives an example of using
634 mongoc_collection_update_one() to update the fields of a document.
635
636 Using the "mydb" database, the following example inserts an example
637 document into the "mycoll" collection. Then, using its _id field, the
638 document is updated with different values and a new field.
639
640 #include <bson/bson.h>
641 #include <mongoc/mongoc.h>
642 #include <stdio.h>
643
644 int
645 main (int argc, char *argv[])
646 {
647 mongoc_collection_t *collection;
648 mongoc_client_t *client;
649 bson_error_t error;
650 bson_oid_t oid;
651 bson_t *doc = NULL;
652 bson_t *update = NULL;
653 bson_t *query = NULL;
654
655 mongoc_init ();
656
657 client =
658 mongoc_client_new ("mongodb://localhost:27017/?appname=update-example");
659 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
660
661 bson_oid_init (&oid, NULL);
662 doc = BCON_NEW ("_id", BCON_OID (&oid), "key", BCON_UTF8 ("old_value"));
663
664 if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
665 fprintf (stderr, "%s\n", error.message);
666 goto fail;
667 }
668
669 query = BCON_NEW ("_id", BCON_OID (&oid));
670 update = BCON_NEW ("$set",
671 "{",
672 "key",
673 BCON_UTF8 ("new_value"),
674 "updated",
675 BCON_BOOL (true),
676 "}");
677
678 if (!mongoc_collection_update_one (
679 collection, query, update, NULL, NULL, &error)) {
680 fprintf (stderr, "%s\n", error.message);
681 goto fail;
682 }
683
684 fail:
685 if (doc)
686 bson_destroy (doc);
687 if (query)
688 bson_destroy (query);
689 if (update)
690 bson_destroy (update);
691
692 mongoc_collection_destroy (collection);
693 mongoc_client_destroy (client);
694 mongoc_cleanup ();
695
696 return 0;
697 }
698
699 Compile the code and run it:
700
701 $ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
702 $ ./update
703
704 On Windows:
705
706 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
707 C:\> update
708 { "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }
709
710 To verify that the update succeeded, connect with the MongoDB shell.
711
712 $ mongo
713 MongoDB shell version: 3.0.6
714 connecting to: test
715 > use mydb
716 switched to db mydb
717 > db.mycoll.find({"updated" : true})
718 { "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
719 >
720
721 Deleting a Document
722 This example illustrates the use of mongoc_collection_delete_one() to
723 delete a document.
724
725 The following code inserts a sample document into the database "mydb"
726 and collection "mycoll". Then, it deletes all documents matching
727 {"hello" : "world"}.
728
729 #include <bson/bson.h>
730 #include <mongoc/mongoc.h>
731 #include <stdio.h>
732
733 int
734 main (int argc, char *argv[])
735 {
736 mongoc_client_t *client;
737 mongoc_collection_t *collection;
738 bson_error_t error;
739 bson_oid_t oid;
740 bson_t *doc;
741
742 mongoc_init ();
743
744 client =
745 mongoc_client_new ("mongodb://localhost:27017/?appname=delete-example");
746 collection = mongoc_client_get_collection (client, "test", "test");
747
748 doc = bson_new ();
749 bson_oid_init (&oid, NULL);
750 BSON_APPEND_OID (doc, "_id", &oid);
751 BSON_APPEND_UTF8 (doc, "hello", "world");
752
753 if (!mongoc_collection_insert_one (collection, doc, NULL, &error)) {
754 fprintf (stderr, "Insert failed: %s\n", error.message);
755 }
756
757 bson_destroy (doc);
758
759 doc = bson_new ();
760 BSON_APPEND_OID (doc, "_id", &oid);
761
762 if (!mongoc_collection_delete_one (
763 collection, doc, NULL, NULL, &error)) {
764 fprintf (stderr, "Delete failed: %s\n", error.message);
765 }
766
767 bson_destroy (doc);
768 mongoc_collection_destroy (collection);
769 mongoc_client_destroy (client);
770 mongoc_cleanup ();
771
772 return 0;
773 }
774
775 Compile the code and run it:
776
777 $ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
778 $ ./delete
779
780 On Windows:
781
782 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
783 C:\> delete
784
785 Use the MongoDB shell to prove that the documents have been removed
786 successfully.
787
788 $ mongo
789 MongoDB shell version: 3.0.6
790 connecting to: test
791 > use mydb
792 switched to db mydb
793 > db.mycoll.count({"hello" : "world"})
794 0
795 >
796
797 Counting Documents
798 Counting the number of documents in a MongoDB collection is similar to
799 performing a find operation. This example counts the number of docu‐
800 ments matching {"hello" : "world"} in the database "mydb" and collec‐
801 tion "mycoll".
802
803 #include <bson/bson.h>
804 #include <mongoc/mongoc.h>
805 #include <stdio.h>
806
807 int
808 main (int argc, char *argv[])
809 {
810 mongoc_client_t *client;
811 mongoc_collection_t *collection;
812 bson_error_t error;
813 bson_t *doc;
814 int64_t count;
815
816 mongoc_init ();
817
818 client =
819 mongoc_client_new ("mongodb://localhost:27017/?appname=count-example");
820 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
821 doc = bson_new_from_json (
822 (const uint8_t *) "{\"hello\" : \"world\"}", -1, &error);
823
824 count = mongoc_collection_count (
825 collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
826
827 if (count < 0) {
828 fprintf (stderr, "%s\n", error.message);
829 } else {
830 printf ("%" PRId64 "\n", count);
831 }
832
833 bson_destroy (doc);
834 mongoc_collection_destroy (collection);
835 mongoc_client_destroy (client);
836 mongoc_cleanup ();
837
838 return 0;
839 }
840
841 Compile the code and run it:
842
843 $ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
844 $ ./count
845 1
846
847 On Windows:
848
849 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
850 C:\> count
851 1
852
854 The driver provides helper functions for executing MongoDB commands on
855 client, database and collection structures. These functions return
856 cursors; the _simple variants return booleans indicating success or
857 failure.
858
859 This example executes the collStats command against the collection "my‐
860 coll" in database "mydb".
861
862 #include <bson/bson.h>
863 #include <mongoc/mongoc.h>
864 #include <stdio.h>
865
866 int
867 main (int argc, char *argv[])
868 {
869 mongoc_client_t *client;
870 mongoc_collection_t *collection;
871 bson_error_t error;
872 bson_t *command;
873 bson_t reply;
874 char *str;
875
876 mongoc_init ();
877
878 client = mongoc_client_new (
879 "mongodb://localhost:27017/?appname=executing-example");
880 collection = mongoc_client_get_collection (client, "mydb", "mycoll");
881
882 command = BCON_NEW ("collStats", BCON_UTF8 ("mycoll"));
883 if (mongoc_collection_command_simple (
884 collection, command, NULL, &reply, &error)) {
885 str = bson_as_canonical_extended_json (&reply, NULL);
886 printf ("%s\n", str);
887 bson_free (str);
888 } else {
889 fprintf (stderr, "Failed to run command: %s\n", error.message);
890 }
891
892 bson_destroy (command);
893 bson_destroy (&reply);
894 mongoc_collection_destroy (collection);
895 mongoc_client_destroy (client);
896 mongoc_cleanup ();
897
898 return 0;
899 }
900
901 Compile the code and run it:
902
903 $ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
904 $ ./executing
905 { "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
906 "lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
907 "indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
908
909 On Windows:
910
911 C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
912 C:\> executing
913 { "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
914 "lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
915 "indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }
916
918 The MongoDB C Driver is thread-unaware in the vast majority of its op‐
919 erations. This means it is up to the programmer to guarantee
920 thread-safety.
921
922 However, mongoc_client_pool_t is thread-safe and is used to fetch a
923 mongoc_client_t in a thread-safe manner. After retrieving a client from
924 the pool, the client structure should be considered owned by the call‐
925 ing thread. When the thread is finished, the client should be placed
926 back into the pool.
927
928 example-pool.c
929
930 /* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
931 * libmongoc-1.0) */
932
933 /* ./example-pool [CONNECTION_STRING] */
934
935 #include <mongoc/mongoc.h>
936 #include <pthread.h>
937 #include <stdio.h>
938
939 static pthread_mutex_t mutex;
940 static bool in_shutdown = false;
941
942 static void *
943 worker (void *data)
944 {
945 mongoc_client_pool_t *pool = data;
946 mongoc_client_t *client;
947 bson_t ping = BSON_INITIALIZER;
948 bson_error_t error;
949 bool r;
950
951 BSON_APPEND_INT32 (&ping, "ping", 1);
952
953 while (true) {
954 client = mongoc_client_pool_pop (pool);
955 /* Do something with client. If you are writing an HTTP server, you
956 * probably only want to hold onto the client for the portion of the
957 * request performing database queries.
958 */
959 r = mongoc_client_command_simple (
960 client, "admin", &ping, NULL, NULL, &error);
961
962 if (!r) {
963 fprintf (stderr, "%s\n", error.message);
964 }
965
966 mongoc_client_pool_push (pool, client);
967
968 pthread_mutex_lock (&mutex);
969 if (in_shutdown || !r) {
970 pthread_mutex_unlock (&mutex);
971 break;
972 }
973
974 pthread_mutex_unlock (&mutex);
975 }
976
977 bson_destroy (&ping);
978 return NULL;
979 }
980
981 int
982 main (int argc, char *argv[])
983 {
984 const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
985 mongoc_uri_t *uri;
986 bson_error_t error;
987 mongoc_client_pool_t *pool;
988 pthread_t threads[10];
989 unsigned i;
990 void *ret;
991
992 pthread_mutex_init (&mutex, NULL);
993 mongoc_init ();
994
995 if (argc > 1) {
996 uri_string = argv[1];
997 }
998
999 uri = mongoc_uri_new_with_error (uri_string, &error);
1000 if (!uri) {
1001 fprintf (stderr,
1002 "failed to parse URI: %s\n"
1003 "error message: %s\n",
1004 uri_string,
1005 error.message);
1006 return EXIT_FAILURE;
1007 }
1008
1009 pool = mongoc_client_pool_new (uri);
1010 mongoc_client_pool_set_error_api (pool, 2);
1011
1012 for (i = 0; i < 10; i++) {
1013 pthread_create (&threads[i], NULL, worker, pool);
1014 }
1015
1016 sleep (10);
1017 pthread_mutex_lock (&mutex);
1018 in_shutdown = true;
1019 pthread_mutex_unlock (&mutex);
1020
1021 for (i = 0; i < 10; i++) {
1022 pthread_join (threads[i], &ret);
1023 }
1024
1025 mongoc_client_pool_destroy (pool);
1026 mongoc_uri_destroy (uri);
1027
1028 mongoc_cleanup ();
1029
1030 return EXIT_SUCCESS;
1031 }
1032
1033
1035 To find information on advanced topics, browse the rest of the C driver
1036 guide or the official MongoDB documentation.
1037
1038 For help with common issues, consult the Troubleshooting page. To re‐
1039 port a bug or request a new feature, follow these instructions.
1040
1042 MongoDB, Inc
1043
1045 2017-present, MongoDB, Inc
1046
1047
1048
1049
10501.23.1 Oct 20, 2022 MONGOC_TUTORIAL(3)