MongoDB c++ driver(三)
插入数据(二)多种常用数据插入的写法#include <chrono>#include <sys/time.h>// #include <bsoncxx/types.hpp>#include <bsoncxx/builder/stream/document.hpp>#include <bsoncxx/json.hpp>#include <mongocxx/client.hpp>#includ
·
插入数据(二)
多种常用数据插入的写法
#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
运行结果:

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)