mongocxx c++ 14标准,进行多表联合查询

发布时间 2023-05-31 23:09:46作者: 我当道士那儿些年

 

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/types.hpp>

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::concatenate;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::kvp;

    
mongocxx::instance inst{}; // 实例化 Mongocxx 库 mongocxx::uri uri("mongodb://localhost:27017"); // 连接 MongoDB URI mongocxx::client conn(uri); // 创建连接实例 mongocxx::database db = conn["test_sh"]; mongocxx::collection teacher_1 = db["teacher_20230417_0_60"]; mongocxx::collection teacher_2 = db["teacher_20230417_120_180"]; // mongocxx::collection teacher_3 = db["teacher_20230417_180_240"]; auto pipeline = mongocxx::pipeline{}; pipeline.lookup({ make_document( kvp("from", "teacher_20230417_120_180"), // b表的表名 kvp("localField", "teacher_1.index_join_id"), // a表的关联外键 kvp("foreignField", "teacher_2.index_join_id"), // b表的关联外键 kvp("as", "teacher_2") // 别名 ) }); pipeline.unwind("$teacher_2"); // 如果有多个,这里需要写多个 /*pipeline.unwind("$array_field1"); pipeline.unwind("$array_field2"); pipeline.unwind("$array_field3");*/ // 这里是做展示代码 pipeline.project({ make_document( kvp("_id", 0), kvp("index", 1), kvp("time", 1), kvp("TPE02", "$teacher_2.TPE02") ) }); // 排序 // pipeline.sort(make_document(kvp("time", 1))); pipeline.limit(10); // 使用.limit()操作符限制结果数量 auto cursor = teacher_1.aggregate(pipeline); for (auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }