Finding a Document

The following guide will step you through the process of connecting to MongoDB and submitting your first query.

Prerequisites

Before you start this guide, ensure you have installed the driver and MongoDB is running on localhost. You can test that MongoDB is up and running by connecting to it with the MongoDB shell.

$ mongo --host localhost 
MongoDB shell version: 2.4.10
connecting to: localhost:27017/test
> 

The Basics

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.

example1.c

Print all documents in a collection.
#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, "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 example1.c.

gcc -o example1 example1.c $(pkg-config --cflags --libs libmongoc-1.0)

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!

./example1

Oops, nothing to print! Let's insert a document into our collection using the MongoDB shell.

[christian@starpulse ~]$ mongo
MongoDB shell version: 2.4.10
connecting to: test
> use test
switched to db test
> db.test.insert({'hello': 'world'})
> 
bye

And now let's run it again!

./example1
{ "_id" : { "$oid" : "534cde1a4f05ea4055d4cd4c" }, "hello" : "world" }

Congratulations on your first query with the MongoDB C Driver!

Specifying a Query

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"}.

example2.c

Finding a specific document.
#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, "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;
}
gcc -o example2 example2.c $(pkg-config --cflags --libs libmongoc-1.0)
./example2
{ "_id" : { "$oid" : "534cde1a4f05ea4055d4cd4c" }, "hello" : "world" }

Our document still matches the query, so it is still printed to stdout. Try changing the element values to see how the results change.