Updating a Document

The following guide will step you through the process of connecting to MongoDB and updating a document.


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. We create a new document, initialized with an _id and a field named hello and insert it into the test.test collection. Then, using that same _id, we update the document, overwriting an existing field and adding a new field.

Lastly, we release all of our heap allocated structures.


Update a document from the collection.
#include <bcon.h>
#include <bson.h>
#include <mongoc.h>
#include <stdio.h>

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, "test", "test");

    bson_oid_init (&oid, NULL);
    doc = BCON_NEW ("_id", BCON_OID (&oid),
                    "hello", BCON_UTF8 ("world!"));

    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        printf ("%s\n", error.message);
        goto fail;

    query = BCON_NEW ("_id", BCON_OID (&oid));
    update = BCON_NEW ("$set", "{",
                           "hello", BCON_UTF8 ("Everybody!"),
                           "updated", BCON_BOOL (true),

    if (!mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error)) {
        printf ("%s\n", error.message);
        goto fail;

    if (doc)
        bson_destroy (doc);
    if (query)
        bson_destroy (query);
    if (update)
        bson_destroy (update);

    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    return 0;

Let's use GCC and pkg-config to compile example4.c.

gcc -o example4 example4.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!


Let's make a query with the MongoDB shell now and see what happened!

[christian@starpulse ~]$ mongo
MongoDB shell version: 2.4.10
connecting to: test
> use test
switched to db test
> db.test.find({})
{ "_id" : { "$oid" : "534cde1a4f05ea4055d4cd4c" }, "hello" : "Everybody!", "updated" : true }