一.安装驱动mongocxx driver
mongocxx 依赖mongo-c-driver ,所以需要先安装mongo-c-driver:https://github.com/mongodb/mongo-c-driver/releases/
1.安装mongo-c-driver
$ wget https://github.com/mongodb/mongo-c-driver/releases/download/1.14.0/mongo-c-driver-1.14.0.tar.gz
$ tar -vxf mongo-c-driver-1.14.0.tar.gz
$ cd mongo-c-driver-1.14.0
$ mkdir cmake-build
$ cd cmake-build
$ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF ..
$ make
$ sudo make install
卸载的话,如下 操作:
$ sudo /usr/local/share/mongo-c-driver/uninstall.sh
以上步骤可参考官方文档:http://mongoc.org/libmongoc/current/installing.html
2.安装mongo-cxx
$ git clone https://github.com/mongodb/mongo-cxx-driver.git --branch releases/stable --depth 1
$ cd mongo-cxx-driver/build
$ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local ..
返回上层目录:
$ make && sudo make install
二、测试mongodb
在mongo-cxx-driver/examples目录下有很多示例,参照create.cpp,修改测试插入1000、10000、一百万条数据插入所需时间
#include <chrono>
#include <bsoncxx/builder/basic/array.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include<time.h>
#include<string>
#include<iostream>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_array;
using bsoncxx::builder::basic::make_document;
int main(int, char**) {
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto db = conn["test"];
// We choose to move in our document here, which transfers ownership to insert_one()
clock_t startTime = clock();
for(int i = 0; i <= 1000; ++i)
{
bsoncxx::document::value restaurant_doc = make_document(
kvp("address",
make_document(kvp("street", "2 Avenue"),
kvp("zipcode", 10075),
kvp("building", "1480"),
kvp("coord", make_array(-73.9557413, 40.7720266)))),
kvp("borough", "Manhattan"),
kvp("cuisine", "Italian"),
kvp("grades",
make_array(
make_document(kvp("date", bsoncxx::types::b_date{std::chrono::milliseconds{12323}}),
kvp("grade", "A"),
kvp("score", 11)),
make_document(
kvp("date", bsoncxx::types::b_date{std::chrono::milliseconds{121212}}),
kvp("grade", "B"),
kvp("score", 17)))),
kvp("name", "Vella"),
kvp("restaurant_id", std::to_string(i)));
auto res = db["restaurants"].insert_one(std::move(restaurant_doc));
}
clock_t endTime = clock();
std::cout << " insert total time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " s" << std::endl;
// @end: cpp-insert-a-document
}
c++ --std=c++11 mginsert.cpp -o mginsert $(pkg-config --cflags --libs libmongocxx)
使用Navicat统计数据:
10万条数据:9.5秒