1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
|
<?xml version="1.0"?>
<page id="tutorial"
type="topic"
xmlns="http://projectmallard.org/1.0/">
<title>Tutorial</title>
<p>This guide offers a brief introduction to the MongoDB C Driver.</p>
<p>For more information on the C API, please refer to the <link xref="index#api-reference">API Documentation</link>.</p>
<links type="section"/>
<section id="installation">
<info><link type="guide" xref="installing"/></info>
<title>0. Installing</title>
<p>For detailed instructions on installing the MongoDB C Driver on a particular platform, please see the <link xref="installing">installation guide</link>.</p>
</section>
<section id="starting-mongod">
<info><link type="guide" xref="index#tutorial"/></info>
<title>1. Starting MongoDB</title>
<p>To run the examples in this tutorial, MongoDB must be installed and running on <code>localhost</code> on the default port, 27017. To check if it is up and running, connect to it with the MongoDB shell.</p>
<screen><output style="prompt">$ mongo --host localhost --port 27017
MongoDB shell version: 3.0.6
connecting to: localhost:27017/test
> </output></screen>
</section>
<section id="connecting">
<info>
<link type="guide" xref="index#tutorial"/>
<link type="guide" xref="advanced-connections"/>
<link type="guide" xref="mongoc_client_new"/>
<link type="guide" xref="mongoc_client_get_database"/>
<link type="guide" xref="mongoc_client_get_collection"/>
</info>
<title>2. Making a Connection</title>
<p>The C Driver provides a convenient way to access MongoDB -- regardless of cluster configuration -- via a <code xref="mongoc_client_t">mongoc_client_t</code>. It transparently connects to standalone servers, replica sets and sharded clusters on demand. Once a connection has been made, handles to databases and collections can be obtained via the structs <code xref="mongoc_database_t">mongoc_database_t</code> and <code xref="mongoc_collection_t">mongoc_collection_t</code>, respectively. MongoDB operations can then be performed through these handles.</p>
<p>At the start of an application, call <link xref="mongoc_init">mongoc_init()</link> before any other libmongoc functions and call <link xref="mongoc_cleanup">mongoc_cleanup()</link> before exiting. When creating handles to clients, databases and servers, call the appropriate destroy functions when finished.</p>
<p>The example below establishes a connection to a standalone server on <code>localhost</code> and performs a simple command. More information about database operations can be found in the <link xref="tutorial#crud-operations">CRUD Operations</link> and <link xref="tutorial#executing-commands">Executing Commands</link> sections. Examples of connecting to replica sets and sharded clusters can be found on the <link xref="advanced-connections">Advanced Connections</link> page.</p>
<listing>
<title><file>connect.c</file></title>
<synopsis><code><![CDATA[#include <bson.h>
#include <bcon.h>
#include <mongoc.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;
bson_t *command,
reply,
*insert;
bson_error_t error;
char *str;
bool retval;
/*
* Required to initialize libmongoc's internals
*/
mongoc_init ();
/*
* Create a new client instance
*/
client = mongoc_client_new ("mongodb://localhost:27017");
/*
* Get a handle on the database "db_name" and collection "coll_name"
*/
database = mongoc_client_get_database (client, "db_name");
collection = mongoc_client_get_collection (client, "db_name", "coll_name");
/*
* Do work. This example pings the database, prints the result as JSON and
* performs an insert
*/
command = BCON_NEW ("ping", BCON_INT32 (1));
retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
if (!retval) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
str = bson_as_json (&reply, NULL);
printf ("%s\n", str);
insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, insert, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (insert);
bson_destroy (&reply);
bson_destroy (command);
bson_free (str);
/*
* Release our handles and clean up libmongoc
*/
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>On a UNIX-like system, the code can be compiled and run like so:</p>
<screen><output style="prompt">$ gcc -o connect connect.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./connect
{ "ok" : 1.000000 }</output></screen>
<p>Alternatively, if <link href="http://www.freedesktop.org/wiki/Software/pkg-config/">pkg-config</link> is not available, paths and libraries can be managed manually.</p>
<screen><output style="prompt">$ gcc -o connect connect.c -I/usr/local/include -lmongoc-1.0 -lbson-1.0
$ ./connect
{ "ok" : 1.000000 }</output></screen>
<p>For Windows users, the code can be compiled and run with the following commands. (This assumes that the MongoDB C Driver has been installed to <code>C:\mongo-c-driver</code>; change the include directory as needed.)</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 connect.c
C:\> connect
{ "ok" : 1.000000 }</output></screen>
</section>
<section id="creating-bson-documents">
<info>
<link type="guide" xref="index#tutorial"/>
<link type="guide" xref="bson:index"/>
</info>
<title>3. Creating BSON Documents</title>
<p>Documents are stored in MongoDB's data format, BSON. The C driver uses <link xref="bson:index">libbson</link> to create BSON documents. There are several ways to construct them: appending key-value pairs, using BCON, or parsing JSON.</p>
<section id="appending">
<info>
<link type="guide" xref="bson:index"/>
<link type="guide" xref="bson:bson_init"/>
<link type="guide" xref="bson:bson_new"/>
</info>
<title>Appending BSON</title>
<p>A BSON document, represented as a <link xref="bson:bson_t">bson_t</link> in code, can be constructed one field at a time using libbson's append functions.</p>
<p>For example, to create a document like this:</p>
<screen><code><![CDATA[{
born : ISODate("1906-12-09"),
died : ISODate("1992-01-01"),
name : {
first : "Grace",
last : "Hopper"
},
languages : [ "MATH-MATIC", "FLOW-MATIC", "COBOL" ],
degrees: [ { degree: "BA", school: "Vassar" }, { degree: "PhD", school: "Yale" } ]
}]]></code></screen>
<p>Use the following code:</p>
<screen><code><![CDATA[#include <bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
const char *lang_names[] = {"MATH-MATIC", "FLOW-MATIC", "COBOL"};
const char *schools[] = {"Vassar", "Yale"};
const char *degrees[] = {"BA", "PhD"};
uint32_t i;
char buf[16];
const char *key;
size_t keylen;
bson_t *document;
bson_t child;
bson_t child2;
char *str;
document = bson_new ();
/*
* Append { "born" : ISODate("1906-12-09") } to the document.
* Passing -1 for the length argument tells libbson to calculate the string length.
*/
born.tm_year = 6; /* years are 1900-based */
born.tm_mon = 11; /* months are 0-based */
born.tm_mday = 9;
bson_append_date_time (document, "born", -1, mktime (&born) * 1000);
/*
* Append { "died" : ISODate("1992-01-01") } to the document.
*/
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
/*
* For convenience, this macro passes length -1 by default.
*/
BSON_APPEND_DATE_TIME (document, "died", mktime (&died) * 1000);
/*
* Append a subdocument.
*/
BSON_APPEND_DOCUMENT_BEGIN (document, "name", &child);
BSON_APPEND_UTF8 (&child, "first", "Grace");
BSON_APPEND_UTF8 (&child, "last", "Hopper");
bson_append_document_end (document, &child);
/*
* Append array of strings. Generate keys "0", "1", "2".
*/
BSON_APPEND_ARRAY_BEGIN (document, "languages", &child);
for (i = 0; i < sizeof lang_names / sizeof (char *); ++i) {
keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
bson_append_utf8 (&child, key, (int) keylen, lang_names[i], -1);
}
bson_append_array_end (document, &child);
/*
* Array of subdocuments:
* degrees: [ { degree: "BA", school: "Vassar" }, ... ]
*/
BSON_APPEND_ARRAY_BEGIN (document, "degrees", &child);
for (i = 0; i < sizeof degrees / sizeof (char *); ++i) {
keylen = bson_uint32_to_string (i, &key, buf, sizeof buf);
bson_append_document_begin (&child, key, (int) keylen, &child2);
BSON_APPEND_UTF8 (&child2, "degree", degrees[i]);
BSON_APPEND_UTF8 (&child2, "school", schools[i]);
bson_append_document_end (&child, &child2);
}
bson_append_array_end (document, &child);
/*
* Print the document as a JSON string.
*/
str = bson_as_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}]]></code></screen>
<p>See the <link xref="bson:bson_t">libbson documentation</link> for all of the types that can be appended to a <code xref="bson:bson_t">bson_t</code>.</p>
</section>
<section id="bcon">
<title>Using BCON</title>
<p><em>BSON C Object Notation</em>, BCON for short, is an alternative way of constructing BSON documents in a manner closer to the intended format. It has less type-safety than BSON's append functions but results in less code.</p>
<screen><code><![CDATA[#include <bson.h>
int
main (int argc,
char *argv[])
{
struct tm born = { 0 };
struct tm died = { 0 };
bson_t *document;
char *str;
born.tm_year = 6;
born.tm_mon = 11;
born.tm_mday = 9;
died.tm_year = 92;
died.tm_mon = 0;
died.tm_mday = 1;
document = BCON_NEW (
"born", BCON_DATE_TIME (mktime (&born) * 1000),
"died", BCON_DATE_TIME (mktime (&died) * 1000),
"name", "{",
"first", BCON_UTF8 ("Grace"),
"last", BCON_UTF8 ("Hopper"),
"}",
"languages", "[",
BCON_UTF8 ("MATH-MATIC"),
BCON_UTF8 ("FLOW-MATIC"),
BCON_UTF8 ("COBOL"),
"]",
"degrees", "[",
"{", "degree", BCON_UTF8 ("BA"), "school", BCON_UTF8 ("Vassar"), "}",
"{", "degree", BCON_UTF8 ("PhD"), "school", BCON_UTF8 ("Yale"), "}",
"]");
/*
* Print the document as a JSON string.
*/
str = bson_as_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
/*
* Clean up allocated bson documents.
*/
bson_destroy (document);
return 0;
}]]></code></screen>
<p>Notice that BCON can create arrays, subdocuments and arbitrary fields.</p>
</section>
<section id="bson-from-json">
<info>
<link type="guide" xref="bson:bson_new_from_json"/>
<link type="guide" xref="bson:bson_init_from_json"/>
<link type="guide" xref="bson:bson_json_reader_t"/>
</info>
<title>Creating BSON from JSON</title>
<p>For <em>single</em> documents, BSON can be created from JSON strings via <link xref="bson:bson_new_from_json">bson_new_from_json</link>.</p>
<screen><code><![CDATA[#include <bson.h>
int
main (int argc,
char *argv[])
{
bson_error_t error;
bson_t *bson;
char *string;
const char *json = "{\"name\": {\"first\":\"Grace\", \"last\":\"Hopper\"}}";
bson = bson_new_from_json ((const uint8_t *)json, -1, &error);
if (!bson) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
string = bson_as_json (bson, NULL);
printf ("%s\n", string);
bson_free (string);
return 0;
}
]]></code></screen>
<p>To initialize BSON from a sequence of JSON documents, use <link xref="bson:bson_json_reader_t">bson_json_reader_t</link>.</p>
</section>
</section>
<section id="crud-operations">
<info><link type="guide" xref="index#tutorial"/></info>
<title>4. Basic CRUD Operations</title>
<p>This section demonstrates the basics of using the C Driver to interact with MongoDB.</p>
<!-- Table of contents -->
<links type="section"/>
<section id="insert" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#basic-operations"/>
<link type="guide" xref="mongoc_collection_insert"/>
</info>
<title>Inserting a Document</title>
<p>To insert documents into a collection, first obtain a handle to a <code>mongoc_collection_t</code> via a <code>mongoc_client_t</code>. Then, use <link xref="mongoc_collection_insert">mongoc_collection_insert()</link> to add BSON documents to the collection. This example inserts into the database "mydb" and collection "mycoll".</p>
<p>When finished, ensure that allocated structures are freed by using their respective destroy functions.</p>
<listing>
<title><file>insert.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it:</p>
<screen><output style="prompt">$ gcc -o insert insert.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./insert</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 insert.c
C:\> insert</output></screen>
<p>To verify that the insert succeeded, connect with the MongoDB shell.</p>
<screen><output style="prompt">$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find()
{ "_id" : ObjectId("55ef43766cb5f36a3bae6ee4"), "hello" : "world" }
> </output></screen>
</section>
<section id="find" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#basic-operations"/>
<link type="guide" xref="mongoc_collection_find"/>
</info>
<title>Finding a Document</title>
<p>To query a MongoDB collection with the C driver, use the function <link xref="mongoc_collection_find">mongoc_collection_find()</link>. This returns a <link xref="mongoc_cursor_t">cursor</link> to the matching documents. The following examples iterate through the result cursors and print the matches to <code>stdout</code> as JSON strings.</p>
<p>Note that <code>mongoc_collection_find</code> uses a document as a query specifier; for example,</p>
<screen><code mime="x-js">{ "color" : "red" }</code></screen>
<p>will match any document with a field named "color" with value "red". An empty document <code>{}</code> can be used to match all documents.</p>
<p>This first example uses an empty query specifier to find all documents in the database "mydb" and collection "mycoll".</p>
<listing>
<title><file>find.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it: </p>
<screen><output style="prompt">$ gcc -o find find.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find.c
C:\> find
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>
<p>To look for a specific document, add a specifier to <code>query</code>. This example adds a call to <code>BSON_APPEND_UTF8()</code> to look for all documents matching <code mime="text/x-js">{"hello" : "world"}</code>.</p>
<listing>
<title><file>find-specific.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_t *query;
char *str;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
query = bson_new ();
BSON_APPEND_UTF8 (query, "hello", "world");
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
while (mongoc_cursor_next (cursor, &doc)) {
str = bson_as_json (doc, NULL);
printf ("%s\n", str);
bson_free (str);
}
bson_destroy (query);
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}]]></code></synopsis>
</listing>
<screen><output style="prompt">$ gcc -o find-specific find-specific.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 find-specific.c
C:\> find-specific
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>
</section>
<section id="update" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#basic-operations"/>
<link type="guide" xref="mongoc_collection_update"/>
<link type="guide" xref="mongoc_collection_find_and_modify"/>
</info>
<title>Updating a Document</title>
<p>This code snippet gives an example of using <link xref="mongoc_collection_update">mongoc_collection_update()</link> to update the fields of a document.</p>
<p>Using the "mydb" database, the following example inserts an example document into the "mycoll" collection. Then, using its <code>_id</code> field, the document is updated with different values and a new field.</p>
<listing>
<title><file>update.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bcon.h>
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_collection_t *collection;
mongoc_client_t *client;
bson_error_t error;
bson_oid_t oid;
bson_t *doc = NULL;
bson_t *update = NULL;
bson_t *query = NULL;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
bson_oid_init (&oid, NULL);
doc = BCON_NEW ("_id", BCON_OID (&oid),
"key", BCON_UTF8 ("old_value"));
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
query = BCON_NEW ("_id", BCON_OID (&oid));
update = BCON_NEW ("$set", "{",
"key", BCON_UTF8 ("new_value"),
"updated", BCON_BOOL (true),
"}");
if (!mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
fail:
if (doc)
bson_destroy (doc);
if (query)
bson_destroy (query);
if (update)
bson_destroy (update);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it:</p>
<screen><output style="prompt">$ gcc -o update update.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./update</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 update.c
C:\> update
{ "_id" : { "$oid" : "55ef43766cb5f36a3bae6ee4" }, "hello" : "world" }</output></screen>
<p>To verify that the update succeeded, connect with the MongoDB shell.</p>
<screen><output style="prompt">$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.find({"updated" : true})
{ "_id" : ObjectId("55ef549236fe322f9490e17b"), "updated" : true, "key" : "new_value" }
> </output></screen>
</section>
<section id="remove" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#basic-operations"/>
<link type="guide" xref="mongoc_collection_remove"/>
</info>
<title>Deleting a Document</title>
<p>This example illustrates the use of <link xref="mongoc_collection_remove">mongoc_collection_remove()</link> to delete documents.</p>
<p>The following code inserts a sample document into the database "mydb" and collection "mycoll". Then, it deletes all documents matching <code>{"hello" : "world"}</code>.</p>
<listing>
<title><file>delete.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_oid_t oid;
bson_t *doc;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "test", "test");
doc = bson_new ();
bson_oid_init (&oid, NULL);
BSON_APPEND_OID (doc, "_id", &oid);
BSON_APPEND_UTF8 (doc, "hello", "world");
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "Insert failed: %s\n", error.message);
}
bson_destroy (doc);
doc = bson_new ();
BSON_APPEND_OID (doc, "_id", &oid);
if (!mongoc_collection_remove (collection, MONGOC_REMOVE_SINGLE_REMOVE, doc, NULL, &error)) {
fprintf (stderr, "Delete failed: %s\n", error.message);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it:</p>
<screen><output style="prompt">$ gcc -o delete delete.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./delete</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 delete.c
C:\> delete</output></screen>
<p>Use the MongoDB shell to prove that the documents have been removed successfully.</p>
<screen><output style="prompt">$ mongo
MongoDB shell version: 3.0.6
connecting to: test
> use mydb
switched to db mydb
> db.mycoll.count({"hello" : "world"})
0
> </output></screen>
</section>
<section id="count" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#basic-operations"/>
<link type="guide" xref="mongoc_collection_count"/>
</info>
<title>Counting Documents</title>
<p>Counting the number of documents in a MongoDB collection is similar to performing a <link xref="tutorial#find">find operation</link>. This example counts the number of documents matching <code mime="text/x-json">{"hello" : "world"}</code> in the database "mydb" and collection "mycoll".</p>
<listing>
<title><file>count.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
int64_t count;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);
count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);
if (count < 0) {
fprintf (stderr, "%s\n", error.message);
} else {
printf ("%" PRId64 "\n", count);
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it: </p>
<screen><output style="prompt">$ gcc -o count count.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./count
1</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 count.c
C:\> count
1</output></screen>
</section>
</section>
<section id="executing-commands" xmlns="http://projectmallard.org/1.0/">
<info>
<link type="guide" xref="index#tutorial"/>
<link type="guide" xref="mongoc_client_command"/>
<link type="guide" xref="mongoc_client_command_simple"/>
<link type="guide" xref="mongoc_database_command"/>
<link type="guide" xref="mongoc_database_command_simple"/>
<link type="guide" xref="mongoc_collection_command"/>
<link type="guide" xref="mongoc_collection_command_simple"/>
</info>
<title>5. Executing Commands</title>
<p>The driver provides helper functions for executing MongoDB commands on client, database and collection structures. These functions return <link xref="mongoc_cursor_t">cursors</link>; the <code>_simple</code> variants return booleans indicating success or failure.</p>
<p>This example executes the <link href="http://docs.mongodb.org/manual/reference/command/collStats/">collStats</link> command against the collection "mycoll" in database "mydb".</p>
<listing>
<title><file>executing.c</file></title>
<synopsis><code mime="text/x-csrc"><![CDATA[#include <bson.h>
#include <bcon.h>
#include <mongoc.h>
#include <stdio.h>
int
main (int argc,
char *argv[])
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *command;
bson_t reply;
char *str;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
collection = mongoc_client_get_collection (client, "mydb", "mycoll");
command = BCON_NEW ("collStats", BCON_UTF8 ("mycoll"));
if (mongoc_collection_command_simple (collection, command, NULL, &reply, &error)) {
str = bson_as_json (&reply, NULL);
printf ("%s\n", str);
bson_free (str);
} else {
fprintf (stderr, "Failed to run command: %s\n", error.message);
}
bson_destroy (command);
bson_destroy (&reply);
mongoc_collection_destroy (collection);
mongoc_client_destroy (client);
mongoc_cleanup ();
return 0;
}
]]></code></synopsis>
</listing>
<p>Compile the code and run it:</p>
<screen><output style="prompt">$ gcc -o executing executing.c $(pkg-config --cflags --libs libmongoc-1.0)
$ ./executing
{ "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
"lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
"indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }</output></screen>
<p>On Windows:</p>
<screen><output style="prompt">C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 executing.c
C:\> executing
{ "ns" : "mydb.mycoll", "count" : 1, "size" : 48, "avgObjSize" : 48, "numExtents" : 1, "storageSize" : 8192,
"lastExtentSize" : 8192.000000, "paddingFactor" : 1.000000, "userFlags" : 1, "capped" : false, "nindexes" : 1,
"indexDetails" : { }, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1.000000 }</output></screen>
</section>
<section id="threading">
<info><link type="guide" xref="index#tutorial"/></info>
<title>6. Threading</title>
<p>The MongoDB C Driver is thread-unaware in the vast majority of its operations. This means it is up to the programmer to guarantee thread-safety.</p>
<p>However, <code xref="mongoc_client_pool_t">mongoc_client_pool_t</code> is thread-safe and is used to fetch a <code>mongoc_client_t</code> in a thread-safe manner. After retrieving a client from the pool, the client structure should be considered owned by the calling thread. When the thread is finished, the client should be placed back into the pool.</p>
<screen><code><![CDATA[#include <mongoc.h>
#include <pthread.h>
#define N_THREADS 10
static void *
worker (void *data) {
mongoc_client_pool_t *pool = data;
mongoc_client_t *client;
client = mongoc_client_pool_pop (pool);
/* Do something... */
mongoc_client_pool_push (pool, client);
return NULL;
}
int
main (int argc,
char *argv[])
{
mongoc_client_pool_t *pool;
mongoc_uri_t *uri;
pthread_t threads[N_THREADS];
mongoc_init ();
uri = mongoc_uri_new ("mongodb://localhost/");
pool = mongoc_client_pool_new (uri);
for (i = 0; i < N_THREADS; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
for (i = 0; i < N_THREADS; i++) {
pthread_join (threads[i], NULL);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return 0;
}
]]></code></screen>
</section>
<section id="next-steps">
<info>
<link type="guide" xref="index#tutorial"/>
<link type="guide" xref="basic-troubleshooting"/>
</info>
<title>7. Next Steps</title>
<p>To find information on advanced topics, browse the rest of the <link xref="index">C driver guide</link> or the <link href="https://docs.mongodb.org">official MongoDB documentation</link>.</p>
<p>For help with common issues, consult the <link xref="basic-troubleshooting">Troubleshooting</link> page. To report a bug or request a new feature, follow <link xref="basic-troubleshooting#file-bug">these instructions</link>.</p>
</section>
</page>
|