您的位置:首页 > 数据库 > Mongodb

MongoDB c++ driver(三)

2016-07-03 11:47 337 查看

插入数据(二)

多种常用数据插入的写法

#include <chrono>
#include <sys/time.h>

// #include <bsoncxx/types.hpp>

#include <chrono>
#include <sys/time.h>

// #include <bsoncxx/types.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;

int main(int argc, char** args)
{
mongocxx::instance inst{};
//chenzw:123 -->用户:密码  参考博客用户管理
mongocxx::client conn{mongocxx::uri{"mongodb://chenzw:123@IP:端口"}};

// auto db = conn["stu"];
// auto collection = conn["stu"]["stu2"];

// document doc{};
// doc << "_id" << 1
// << "name" << "second example"
// << "info" << "insert a document";

// collection.insert_one(doc.view());

//官网的例子
auto db = conn["guanwang"];

struct timeval t;
gettimeofday(&t, NULL);

bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"//打开新的子文档
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array //插入数组
<< close_document << "borough"//关闭子文档
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
//<< bsoncxx::types::b_date{std::chrono::milliseconds{12323}} << "grade"
<< bsoncxx::types::b_date{0} << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
//<< bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade"
// << bsoncxx::types::b_date{t.tv_sec * 1000 + t.tv_usec} << "grade"
<< bsoncxx::types::b_date{t.tv_sec * 1000 + t.tv_usec/1000} << "grade" //执行时时间
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;

// We choose to move in our document here, which transfers ownership to insert_one()
auto res = db["restaurants"].insert_one(std::move(restaurant_doc));

return 0;
}


编译、运行

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

$ ./2insertData2

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb