The following guide will step you through the process of connecting to MongoDB and submitting your first query.
The following code example creates a new mongoc_client_t
that we will use to communicate with MongoDB.
The Connection String URI component is quite comprehensive.
Using our mongoc_client_t
, we get a handle to a mongoc_collection_t
which represents the remote collection.
query
is initialized to a new BSON document that contains no elements, therefore matching every document in the MongoDB collection.
Using the returned cursor, we convert each resulting document to a MongoDB Extended JSON string and print it to stdout
.
Lastly, we release all of our heap allocated structures.
#include
#include
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, "test", "test");
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);
return 0;
}
]]>
Let's use GCC
and pkg-config
to compile
When using the MongoDB C Driver, you must call mongoc_init() at the beginning of your application. This allows the driver to initialize it's required subsystems. Failure to do so will result in a runtime crash.
Now let's run it!
Oops, nothing to print! Let's insert a document into our collection using the MongoDB shell.
And now let's run it again!
Congratulations on your first query with the MongoDB C Driver!
The above example is useful, but wouldn't it be more useful if we could find a specific document?
Let's modify the above program to find a specific document matching {"hello": "world"}
.
#include
#include
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, "test", "test");
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);
return 0;
}
]]>
Our document still matches the query, so it is still printed to stdout
.
Try changing the element values to see how the results change.