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