Deleting a Document

The following guide will step you through the process of connecting to MongoDB and deleting 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. Immediately after, we remove the document matching the _id we inserted.

Lastly, we release all of our heap allocated structures.

example4.c

Removing a document from 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;
    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 ("Insert failed: %s\n", error.message);
    }

    bson_destroy (doc);

    doc = bson_new ();
    BSON_APPEND_OID (doc, "_id", &oid);

    if (!mongoc_collection_delete (collection, MONGOC_DELETE_SINGLE_REMOVE, doc, NULL, &error)) {
        printf ("Delete failed: %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 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!

./example4