Access MongoDB in C

Overview

Using the C driver from the MongoDB official I made a sample to access MongoDB, so I would like to share the source and procedure.

Environment

Assuming CentOS.

Added Mongo repository. Create a new mongodb.repo.

diff:/etc/yum.repos.d/mongodb.repo


[mongodb-org-3.6]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

centos7


yum update -y
yum install -y mongodb-org  #mongodb installation
#mongodb driver installation
yum install -y make git gcc automake autoconf libtool pkg-config openssl-devel cyrus-sasl-devel wget tar  #What you need to install the driver

wget https://github.com/mongodb/mongo-c-driver/releases/download/1.9.5/mongo-c-driver-1.9.5.tar.gz
tar xzf mongo-c-driver-1.9.5.tar.gz 
cd mongo-c-driver-1.9.5
./configure
sudo make
sudo make install

Database settings

I will put in the data for the test.

service mongod start     #start mongodb server
mongo                    #mongodb server connection
use db_test              #DB creation
#Collection creation, document input
db.cl_test.insert({id:1, name:'aaa'});
db.cl_test.insert({id:2, name:'bbb'});
db.cl_test.insert({id:3, name:'ccc'});
exit

Access to MongoDB

mongo.c


#include <bson.h>
#include <bcon.h>
#include <mongoc.h>
#include <stdio.h>
#include <stdlib.h>

int main( void ){
  mongoc_client_t *     conn    = NULL;
  mongoc_collection_t * coll    = NULL;
  mongoc_cursor_t *     cusr    = NULL;
  const bson_t *        doc     = NULL;
  char *                ret_str = NULL;
  bson_t                query;
  //DB connection
  conn = mongoc_client_new (
             "mongodb://localhost:27017/"  //Destination URI
         );
  if( NULL == conn ){
    // error
    exit(-1);
  }
  //Data acquisition
  coll = mongoc_client_get_collection (
           conn   ,    //connection
           "db_test" , //DB name
           "cl_test"   //Collection name
         );
  if( NULL == coll ){
    // error
    mongoc_client_destroy ( conn );
    exit(-1);
  }
  bson_init (&query);
  cusr = mongoc_collection_find (
           coll              , //collection
           MONGOC_QUERY_NONE , // mongoc_query_flags_t(Specify no search conditions)
           0                 , //Starting position(Get from the beginning)
           0                 , //Maximum number of acquisitions(Get all)
           0                 , //batch size(default specification(=100) )
           &query            , //Query(unspecified)
           NULL              , //field(For all)
           NULL                //Capture cluster(default specification(=Get from primary))
         );
  if( NULL == cusr ){
    // error
    mongoc_client_destroy ( conn );
    bson_destroy (&query);
    exit(-1);
  }
  while (mongoc_cursor_next ( cusr , &doc ) ) {
    ret_str = bson_as_json ( doc , NULL );
    printf ( "%s\n", ret_str );
    bson_free ( ret_str );
  }
  //Clean up
  mongoc_collection_destroy( coll );
  mongoc_client_destroy ( conn );
  bson_destroy (&query);
  return 0;
}

Compile and run

I couldn't find the library as it was Create mongo.conf, register it, and then execute it.

diff:/etc/ld.so.conf.d/mongo.conf


/usr/local/lib
ldconfig #Reflect settings
gcc -Wall -o mongo mongo.c -lmongoc-1.0 -lbson-1.0 -L/usr/local/lib -I/usr/local/include/libmongoc-1.0/ -I/usr/local/include/libbson-1.0/
./mongo
{ "_id" : { "$oid" : "54bfc04676613f50e453d617" }, "id" : 1.000000, "name" : "aaa" }
{ "_id" : { "$oid" : "54bfc04676613f50e453d618" }, "id" : 2.000000, "name" : "bbb" }
{ "_id" : { "$oid" : "54bfc04976613f50e453d619" }, "id" : 3.000000, "name" : "ccc" }

It seems that you have to parse JSON in C.

Recommended Posts

Access MongoDB in C
mongodb access with pymongo
Next Python in C
C API in Python 3
Extend python in C ++ (Boost.NumPy)
Machine language embedding in C language
Heapsort made in C language
Use regular expressions in C
Use MongoDB ODM in Python
Imitated Python's Numpy in C #
Binary search in Python / C ++
python in mongodb in descending sort
Minimum spanning tree in C #
Access the C structure field with the name reserved in Go.
Write a table-driven test in C
Multi-instance module test in C language
Realize interface class in C language
ABC166 in Python A ~ C problem
Try PLC register access in Python
Try to put data in MongoDB
When reading C ++ structs in Cython
Solve ABC036 A ~ C in Python
How to wrap C in Python
How to build MongoDB C driver
Solve ABC037 A ~ C in Python
Access the Twitter API in Python
Segfault with 16 characters in C language
Write C unit tests in Python
Linked list (list_head / queue) in C language
Solve ABC175 A, B, C in Python
How to access environment variables in Python
Algorithm in Python (ABC 146 C Binary Search
Revived from "no internet access" in Python
Implement part of the process in C ++
Implement FIR filters in Python and C
How to use Google Test in C
Write O_SYNC file in C and Python
Exclusive file access between processes in Python
I wrote the selection sort in C
MongoDB for the first time in Python
[AWS] Switch access rights in boto3 Session
Generate C language from S-expressions in Python
Export xlsx file in C ++ using libxlsxwriter.
Access S3 resources via Cognito in Python
Run Python in C ++ on Visual Studio 2017
Communicate with I2C devices in Linux C