mongocxx基本增删改查操作

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”建立索引

参考链接:https://mongodb.github.io/mongo-cxx-driver/

 http://mongodb.github.io/mongo-cxx-driver/api/mongocxx-3.1.1/classbsoncxx_1_1document_1_1element.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值