MongoDB using C


This document is an introduction to the usage of the MongoDB database from a C program.

First, install MongoDB – see this blog for how to install and here we will work on MSYS software.

What is MSYS software?


MSYS is a collection of GNU utilities such as bash, make, gawk and grep to allow the building of applications and programs which depend on traditionally UNIX tools to be present.

A common misunderstanding is MSYS is "UNIX on Windows", MSYS by itself does not contain a compiler or a C library, therefore does not give the ability to magically port UNIX programs over to Windows nor does it provide any UNIX specific functionality like case-sensitive filenames.

Why are We using this?

An example would be building a library that uses the build system. Users will typically run "./configure" then "make" to build it. The configure shell script requires a shell script interpreter which is not present on Windows systems, but provided by MSYS.

To establish a connection in Mongodb by C and C++, you will get the source code of the driver for it, which will have to be implemented according to your platform.


How to install MSYS Software and MongoDB C Driver

Download MSYS after Download Install It.
open command prompt you can now move to c:\msys64 there type mingw64 to start the environment 

type pacman -Syu
exit the window

again open and type pacman -Syu (this will take a lot of time please wait)

install all module one by one:-
--pacman --noconfirm -S mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake

--pacman --noconfirm -S mingw-w64-x86_64-extra-cmake-modules make tar

--pacman --noconfirm -S mingw64/mingw-w64-x86_64-cyrus-sasl

--curl -LO https://github.com/mongodb/mongo-c-driver/releases/download/1.16.2/mongo-c-driver-1.16.2.tar.gz

--tar xzf mongo-c-driver-1.16.2.tar.gz

--cd mongo-c-driver-1.16.2

--mkdir cmake-build

--cd cmake-build

--CC=/mingw64/bin/gcc.exe /mingw64/bin/cmake -G "MSYS Makefiles" -DCMAKE_INSTALL_PREFIX="C:/mongo-c-driver" -DCMAKE_C_FLAGS="-D__USE_MINGW_ANSI_STDIO=1" ..

--make install

Now check-in mongo-c-driver you will find  "bin" this contains dll file which is window specific according to your system platform "include", "lib" and "share" folder in parallel

Initialization

Initialize the MongoDB C Driver by calling mongoc_init() exactly once at the beginning of your program. It is responsible for initializing global state such as process counters, SSL, and threading primitives.


mongo_init();


Connection

let create a connection to the database and access or create a collection


mongoc_client_t *client;
mongoc_collection_t *collection;

client=mongoc_client_new("mongodb://localhost:27017");
collection=mongoc_client_get_collection(client,"tmdb","students");


Here we establish a connection to MongoDB server and we assign a database and collection reference to "collection" variable. if there exists a database/collection then it return existing reference if not exist then it will create a new database/collection and return to the variable

 Creating Document

The MongoDB database stores data in BSON format. BSON is a binary object format that is JSON-like in terms of the data which can be stored (some extensions exist, for example, a Date datatype). So we create a document here a document is a struct and store all data in it


bson_t *doc;

doc=bson_new();
BSON_APPEND_UTF8(doc,"rollNumber","101");
BSON_APPEND_UTF8(doc,"firstName","Prakash");
BSON_APPEND_UTF8(doc,"lastName","Pandey");


Insert

We insert a document "doc" to a collection using  mongoc_collection_insert_one()


bson_error_t error;

mongoc_collection_insert_one(collection,doc,NULL,NULL,&error)

As mongoc_collection_insert_one() required 5 parameter 

Collection: as mongo_Collection_t reference to a database/collection 

Document: as A bson_t new created document need to insert, 

Opts: may be NULL or a BSON document with additional command.

Reply: it is Optional. An uninitialized bson_t populated with the insert result, or NULL. 

Error: An optional location for a bson_error_t or NULL


Releasing Memory

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by the programmer. So we need to free all memory allocated


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

Call mongo_cleanup() exactly once at the end of your program to release all memory and other resources allocated by the driver. You must not call any other MongoDB C Driver functions after mongoc_cleanup.

Let grab all in one call eg1.c 


eg1.c

#include<mongoc.h>
#include<stdio.h>
int main()
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
mongoc_init();
client=mongoc_client_new("mongodb://localhost:27017");
collection=mongoc_client_get_collection(client,"tmdb","students");

doc=bson_new();
BSON_APPEND_UTF8(doc,"rollNumber","101");
BSON_APPEND_UTF8(doc,"firstName","Prakash");
BSON_APPEND_UTF8(doc,"lastName","Pandey");
if(!mongoc_collection_insert_one(collection,doc,NULL,NULL,&error))
{
printf("%s\n",error.message);
}
bson_destroy(doc);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup(); 
printf("DONE");
return 0;
}

compile :-
gcc eg1.c -o eg1.out -I /mongo-c-driver/include/libmongoc-1.0/ -I /mongo-c-driver/include/libbson-1.0/ -L . libmongoc-1.0.dll.a libbson-1.0.dll.a

execute:- ./eg1.out


This end of insertion document in collection/database similarly you can do update, delete and find a document in database/collection;

Update


eg2.c

#include<mongoc.h>
#include<stdio.h>
int main()
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
bson_t *quary;
mongoc_init();
client=mongoc_client_new("mongodb://localhost:27017");
collection=mongoc_client_get_collection(client,"tmdb","student");
quary=bson_new();
BSON_APPEND_UTF8(quary,"rollNumber","101");
doc=bson_new();
BSON_APPEND_UTF8(doc,"firstName","Ram");
BSON_APPEND_UTF8(doc,"lastName","Pandey");
if(!mongoc_collection_update(collection,MONGOC_UPDATE_NONE,quary,doc,NULL,&error))
{
printf("%s\n",error.message);
}
else
{
printf("updated\n");
}
bson_destroy(quary);
bson_destroy(doc);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup(); 
printf("DONE");
return 0;
}

compile :-
gcc eg2.c -o eg2.out -I /mongo-c-driver/include/libmongoc-1.0/ -I /mongo-c-driver/include/libbson-1.0/ -L . libmongoc-1.0.dll.a libbson-1.0.dll.a

execute:- ./eg2.out

Delete


eg3.c

#include<mongoc.h>
#include<stdio.h>
int main()
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
bson_t *quary;
mongoc_init();
client=mongoc_client_new("mongodb://localhost:27017");
collection=mongoc_client_get_collection(client,"tmdb","students");
quary=bson_new();
BSON_APPEND_UTF8(quary,"rollNumber","101");
if(!mongoc_collection_remove(collection,MONGOC_REMOVE_NONE,quary,NULL,&error))
{
printf("%s\n",error.message);
}
else
{
printf("removed\n");
}
bson_destroy(quary);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup(); 
printf("DONE");
return 0;
}

compile :-
gcc eg3.c -o eg3.out -I /mongo-c-driver/include/libmongoc-1.0/ -I /mongo-c-driver/include/libbson-1.0/ -L . libmongoc-1.0.dll.a libbson-1.0.dll.a

execute:- ./eg3.out

Find a document in a collection


eg4.c

#include<mongoc.h>
#include<stdio.h>
int main()
{
mongoc_client_t *client;
mongoc_collection_t *collection;
bson_error_t error;
mongoc_cursor_t *cursor;
const bson_t *document;
const bson_t query=BSON_INITIALIZER;
char *str;

mongoc_init();
client=mongoc_client_new("mongodb://localhost:27017");
collection=mongoc_client_get_collection(client,"tmdb","student");

cursor = mongoc_collection_find_with_opts (collection,&query, NULL, NULL);
while (mongoc_cursor_next (cursor, &document)) 
{
str = bson_as_json (document, NULL);
printf ("%s\n", str);
bson_free (str);
}
if(mongoc_cursor_error(cursor,&error))
{
printf("problem%s",error.message);
}
mongoc_cursor_destroy (cursor);
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup(); 
printf("DONE");
return 0;
}

compile :-
gcc eg4.c -o eg4.out -I /mongo-c-driver/include/libmongoc-1.0/ -I /mongo-c-driver/include/libbson-1.0/ -L . libmongoc-1.0.dll.a libbson-1.0.dll.a

execute:- ./eg4.out

Hope you find it helpful and feel free to add a comment and I’ll make sure to improve my self.

Thank You

Prakash Pandey


Comments

Post a Comment

Popular posts from this blog

MongoDB using Java

Lambda Expression in Java

Designing the Buyer Centric Funnel