Ubuntu16.04环境下安装mongodb c++ driver 见同类别上一篇博客。
目前参与的项目算法部分暂时收工,老师布置了新任务,把视频特征使用mongodb管理起来……现学现卖~
使用KDevelop开发
cmake版本:3.5
链接mongodb数据库,并插入{“hello”,”world”}
上一篇博客的test.cpp来自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{}};//执行代码之前打开mongodb服务 sudo service mongod start,这里没有设置用户名和密码,额因为并没有在数据库中创建用户,先这么放着吧,之后再学。
bsoncxx::builder::stream::document document{};
auto collection = conn["testdb"]["testcollection"];//可以理解成为testdb数据库的testcollection表
document << "hello" << "world";
collection.insert_one(document.view());//insert_one需要对“表”进行操作,所以如果collection初始化为conn["testdb"],这里会报错,因为insert_one还有下一行的find不是mongocxx::v_noabi::database的成员函数。
auto cursor = collection.find({});
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
debug结果,控制台输出:
附CMakelists.txt
cmake_minimum_required(VERSION 2.6)
project(mongodbtest)
include_directories(/usr/local/include/bsoncxx/v_noabi /usr/local/include/mongocxx/v_noabi)
add_executable(mongodbtest main.cpp)
install(TARGETS mongodbtest RUNTIME DESTINATION bin)
target_link_libraries(mongodbtest bsoncxx mongocxx snappy)