官網 http://mongoc.org/libmongoc/current/tutorial.html
下載 wget https://github.com/mongodb/mongo-c-driver/releases/download/1.6.3/mongo-c-driver-1.6.3.tar.gz
$ tar xzf mongo-c-driver-1.6.3.tar.gz
$ cd mongo-c-driver-1.6.3
$ ./configure --disable-automatic-init-and-cleanup
Starting MongoDB¶
To run the examples in this tutorial, MongoDB must be installed and running on localhost on the default port, 27017. To check if it is up and running, connect to it with the MongoDB shell.
$ mongo --host localhost --port 27017MongoDB shell version: 3.0.6connecting to: localhost:27017/test>
Making a Connection¶
The C Driver provides a convenient way to access MongoDB -- regardless of cluster configuration -- via a mongoc_client_t. 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 mongoc_database_t and mongoc_collection_t, respectively. MongoDB operations can then be performed through these handles.
At the start of an application, call mongoc_init() before any other libmongoc functions and call mongoc_cleanup() before exiting. When creating handles to clients, databases and servers, call the appropriate destroy functions when finished.
The example below establishes a connection to a standalone server on localhost, registers the client application as "connect-example," and performs a simple command. More information about database operations can be found in the CRUD Operations and Executing Commands sections. Examples of connecting to replica sets and sharded clusters can be found on the Advanced Connections page.
#include <bson.h>#include <bcon.h>#include <mongoc.h>intmain (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"); /* * Register the application name so we can track it in the profile logs * on the server. This can also be done from the URI (see other examples). */ mongoc_client_set_appname (client, "connect-example"); /* * 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;}
On a UNIX-like system, the code can be compiled and run like so:
$ gcc -o connect connect.c $(pkg-config --cflags --libs libmongoc-1.0)$ ./connect{ "ok" : 1.000000 }
Alternatively, if pkg-config is not available, paths and libraries can be managed manually.
$ gcc -o connect connect.c -I/usr/local/include -lmongoc-1.0 -lbson-1.0$ ./connect{ "ok" : 1.000000 }
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 C:\mongo-c-driver; change the include directory as needed.)
C:\> cl.exe /IC:\mongo-c-driver\include\libbson-1.0 /IC:\mongo-c-driver\include\libmongoc-1.0 connect.cC:\> connect{ "ok" : 1.000000 }
Creating BSON Documents¶
Documents are stored in MongoDB's data format, BSON. The C driver uses libbson to create BSON documents. There are several ways to construct them: appending key-value pairs, using BCON, or parsing JSON. Appending BSON¶
A BSON document, represented as a bson_t in code, can be constructed one field at a time using libbson's append functions.
For example, to create a document like this:
{ 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" } ]}
Use the following code:
#include <bson.h>intmain (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;}
See the libbson documentation for all of the types that can be appended to a bson_t. Using BCON¶
BSON C Object Notation, 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.
#include <bson.h>intmain (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"), "]",