mongodb 的C++驱动分为mongocxx和legacy(旧版本)两个版本。2个版本的驱动安装和API都不相同。现在仅介绍mongocxx版本的操作。
#include <iostream>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include<mongocxx/instance.hpp>
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
usingbsoncxx::builder::stream::open_document;
mongocxx::instance instance{}; // This should be doneonly once.
mongocxx::uri uri("mongodb://localhost:27018");
mongocxx::client client(uri);
mongocxx::database db = client["mydb"];//获取数据库“mydb”,如果client是指针类型,则可以通过database()方法获取。
//获取集合
mongocxx::collection coll = db["test"];//获取test集合
auto builder =bsoncxx::builder::stream::document{};
bsoncxx::document::value doc_value = builder
<< "name" << "MongoDB"
<< "type" << "database"
<< "count" << 1
<< "versions" <<bsoncxx::builder::stream::open_array
<< "v3.2" << "v3.0" << "v2.6"
<< close_array
<< "info" <<bsoncxx::builder::stream::open_document
<< "x"<< 203
<< "y" << 102
<<bsoncxx::builder::stream::close_document
<< bsoncxx::builder::stream::finalize;
//插入一条数据
coll.insert_one(doc_value.view());
//删除一条数据
coll.delete_one(document{}<<" name "<<"MongoDB"<<
" type "<< " database "<<finalize);
//更新一条数据
collSiaNeName.update_one(document{}<<
" name "<<"MongoDB" <<finalize,
document{}<<"$set"<<open_document
<<"type"<<"data"
<<close_document
<<finalize);
//查询一个集合
mongocxx::stdx::optional<bsoncxx::document::value> result = coll.find_one(document{} <<" name"<<"MongoDB"<<finalize);
if(result){
bsoncxx::document::view view = (*result).view();
std::string Name = view["name"].get_utf8().value.to_string(); //获取查询到的name的值,若是double类型则为view["name"].get_double();
}
//建立索引
coll.create_index(std::move(document{}<<" name"<<1<<finalize));//对“name”建立索引,1为按升序创建索引,-1为按降序创建索引
coll.create_index(std::move(document{}<<" name"<<1<<” type”<<1<<finalize));//对“name”和“type”建立索引