Linux C/C++呼叫mongDB

嚇人的猿發表於2018-03-03

c呼叫mongoDB

安裝mongoDB-c-driver

  1. 安裝必要軟體

sudo apt-get install git autoconf automake libtool
  1. 下載mongoDB原始碼包

$ git clone https://github.com/mongodb/mongo-c-driver.git
$ cd mongo-c-driver
$ ./autogen.sh --with-libbson=bundled
$ make
$ sudo make install
  1. 將標頭檔案以及庫加入到系統路徑中

export C_INCLUDE_PATH=$C_INCLUDE_PATH:/usr/local/include/libmongoc-1.0/:/usr/local/include/libbson-1.0/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/lib

使用mongoDB-c-driver程式設計

初始化mongoc

非執行緒安全,只需呼叫一次

mongoc_init();

連線mongodb

const char *uristr = "mongodb://127.0.0.1/";
mongoc_client_t* m_pClient = mongoc_client_new(uristr);

獲取collection

mongoc_collection_t * m_pCollection = mongoc_client_get_collection(m_pClient, "test_db", "test_collection"); 

插入記錄

bson_error_t error;
bson_t *doc = bson_new();
BSON_APPEND_INT64(doc, "id", 1);
BSON_APPEND_INT64(doc, "field1", 0);
char msg[] = "test message";
BSON_APPEND_BINARY(doc, "field2", BSON_SUBTYPE_BINARY, msg, strlen(msg));

int r = mongoc_collection_insert(m_pCollection, MONGOC_INSERT_NONE, doc, NULL, &error);
if (r == 0)
{
    printf("Insert Failure:%s\n",  error.message);
}
bson_destroy(doc);

完整程式碼:


#include <stdio.h>
#include <mongoc.h>
#include <bson.h>
int main() {

    const char *uristr = "mongodb://192.168.1.105/";
    mongoc_init();
    mongoc_client_t* m_pClient = mongoc_client_new(uristr);
    mongoc_collection_t * m_pCollection = mongoc_client_get_collection(m_pClient, "test_db", "test_collection");

    bson_error_t error;
    bson_t *doc = bson_new();
    BSON_APPEND_INT64(doc, "id", 1);
    BSON_APPEND_INT64(doc, "field1", 0);
    char msg[] = "test message";
    BSON_APPEND_BINARY(doc, "field2", BSON_SUBTYPE_BINARY, msg, strlen(msg));

    int r = mongoc_collection_insert(m_pCollection, MONGOC_INSERT_NONE, doc, NULL, &error);
    if (r == 0)
    {
        printf("Insert Failure:%s\n",  error.message);
    }
    bson_destroy(doc);
    mongoc_client_destroy(m_pClient);
    return 0;
}

更新記錄

/*{$set:{field1:22}}*/
bson_error_t error;
bson_t *doc = bson_new();
bson_t child;
bson_append_document_begin(doc, "$set", -1, &child);
BSON_APPEND_INT64(&child, "field1", 22);
bson_append_document_end(doc, &child);


/*{id:1}*/
bson_t query;
bson_init(&query);
BSON_APPEND_INT64(&query, "id", 1);

int r = mongoc_collection_update(m_pCollection, MONGOC_UPDATE_NONE,
                    &query, doc, NULL, &error);
if (r == 0)
{
    printf("Update Failure: %s\n", error.message);
}
bson_destroy(&query);
bson_destroy(doc);

完整程式碼:


#include <stdio.h>
#include <mongoc.h>
#include <bson.h>
int main() {

    const char *uristr = "mongodb://192.168.64.10/";
    mongoc_init();
    mongoc_client_t* m_pClient = mongoc_client_new(uristr);
    mongoc_collection_t * m_pCollection = mongoc_client_get_collection(m_pClient, "test_db", "test_collection");

    bson_error_t error;
    bson_t *doc = bson_new();
    bson_t child;
    bson_append_document_begin(doc, "$set", -1, &child);
    BSON_APPEND_INT64(&child, "field1", 22);
    bson_append_document_end(doc, &child);

    bson_t query;
    bson_init(&query);
    BSON_APPEND_INT64(&query, "id", 1);

    int r = mongoc_collection_update(m_pCollection, MONGOC_UPDATE_NONE,
                                    &query, doc, NULL, &error);
    if (r == 0)
    {
        printf("Update Failure: %s\n", error.message);
    }
    bson_destroy(&query);
    bson_destroy(doc);
    mongoc_client_destroy(m_pClient);

    return 0;
}

刪除記錄

bson_error_t error;
bson_t query;
bson_init(&query);
BSON_APPEND_INT64(&query"id"1);
int r = mongoc_collection_remove(m_pCollection, MONGOC_DELETE_NONE,
             &query, NULL,  &error);
if (r == 0)
{
    printf("Delete Failure: %s\n", error.message);
}
bson_destroy(&query);

完整程式碼:


#include <stdio.h>
#include <mongoc.h>
#include <bson.h>
int main() {

    const char *uristr = "mongodb://192.168.1.105/";
    mongoc_init();
    mongoc_client_t* m_pClient = mongoc_client_new(uristr);
    mongoc_collection_t * m_pCollection = mongoc_client_get_collection(m_pClient, "test_db", "test_collection");

    bson_error_t error;
    bson_t query;
    bson_init(&query);
    BSON_APPEND_INT64(&query, "id", 1);
    int r = mongoc_collection_remove(m_pCollection, MONGOC_DELETE_NONE,
                     &query, NULL,  &error);
    if (r == 0)
    {
            printf("Delete Failure: %s\n", error.message);
    }
    bson_destroy(&query);

    mongoc_client_destroy(m_pClient);
    return 0;
}

編譯命令

gcc mongoDBtest.c -lmongoc-1.0 -lbson-1.0

官方api

http://api.mongodb.com/

C++呼叫mongoDB

linux下安裝mongoDB

  • 下載mongo_2_2_3.tar.gz資料庫的執行包

  • tar zxvf mongo22_3.tar.gz

  • mkdir ~/mongoDB

  • ./bin/mongod --dbpath ~/mongoDB

執行成功如下圖:

安裝mongoDB C++驅動庫

​ 需要 libbson 和 MongoDB C driver預先安裝配置妥當,而MongoDB C driver又要求automakeautoconf and libtoolMongoDB C++ driver要求gitpkg-config

sudo apt-get install git pkg-config cmake -y

安裝完畢後檢視cmake版本

cmake -version

安裝mongDB C++驅動

下載地址https://github.com/mongodb/mongo-cxx-driver/releases

tar -zxvf mongo-cxx-driver-r3.0.2.tar.gz 
cd mongo-cxx-driver-r3.0.2/build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local

​ 注意第四步中使用選項 -DCMAKE_INSTALL_PREFIX=/usr/local 來指定將要安裝C++驅動的路徑如果不指定的話,將預設安裝在 mongo-cxx-driver-r3.0.2/build/install 路徑下將會導致找不到相應的標頭檔案和庫而無法編譯

sudo make
sudo make install

​ 注意第二步一定要使用sudo來做,因為在上面生成makefile檔案時指定了安裝到 /usr/local/ 這個路徑下該路徑需要root許可權才能寫入

​ 安裝成功後,可以看到 /usr/local/lib 目錄下已經成功的生成了相關的庫檔案,如下圖所示

​ 最後測試一下驅動,使用Mongodb官方給的測試程式碼,程式碼如下:

#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>

int main(int, char**)
{
    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{}};

    bsoncxx::builder::stream::document document{};

    auto collection = conn["testdb"]["testcollection"];
    document << "hello" << "world";

    collection.insert_one(document.view());
    auto cursor = collection.find({});

    for (auto && doc : cursor)
    {
        std::cout << bsoncxx::to_json(doc) << std::endl;
    }
}

使用下面的命令進行編譯: 

c++ --std=c++11 hellomongo.cpp -o hellomongo $(pkg-config --cflags --libs libmongocxx)

相關文章