author-pic

Abid Zaidi

MongoDB in C using mongoc library


Published on September 10, 2021

Intro

Mongoc is a client library in C for MongoDB. It packs with a libbson library that makes it easier to parse and process bson document data (just like libjansson). Github Link


Download and install

Installing mongoc on Ubuntu is very simple, you can follow their documentation, but that doesn't work very well, advisable is,

  sudo  apt-get install libmongoc-dev
  sudo  apt-get install libbson-dev
  sudo  apt-get install libbson-1.0-0

Running Bootstrap code

Below is a sample code which inserts a IP and port to a collection in a while log twice every second, you could look into different formats provided by bson link

#include<stdio.h>
#include <mongoc.h>

int main(){

    mongoc_client_t *client;
    mongoc_collection_t *collection;

    mongoc_init();
    client = mongoc_client_new("mongodb://11.1.1.15:27017/");
    collection = mongoc_client_get_collection(client, "dummy", "ip_dumps");

        bson_error_t error;

        while(true){

                bson_t *doc;

                doc = bson_new();

                // UTF8 for string values while INT32 for integer values

                BSON_APPEND_UTF8(doc, "public_ip", "111.19.27.23");
                BSON_APPEND_INT32(doc, "port", "88932");



                if (!mongoc_collection_insert_one(collection, doc, NULL, NULL, &error))
                {
                        fprintf(stderr, "%s\n", error.message);
                }

                bson_destroy(doc);
                sleep(0.5);
        }


        // clear out mongodb
        mongoc_collection_destroy(collection);
        mongoc_client_destroy(client);
        mongoc_cleanup();


}

In order to compile and run
gcc -o mongo mongodb.c $(pkg-config --cflags --libs libmongoc-1.0)
./mongo

👨‍💻 Happy coding 👨‍🦯

If you like it, share it!


Abid Zaidi's DEV diary

Built with Gatsby Theme by @willjw3