Inserting a Document

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

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. See the Connection String URI page for more information on connecting to MongoDB.

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.

Lastly, we release all of our heap allocated structures.

example3.c

Insert a document into the 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;
    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)) {
        printf ("%s\n", error.message);
    }

    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    return 0;
}

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

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

./example3

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" : "world" }
> 
bye