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