这是一种方法。在此示例中,bsoncxx::types 比我想解码的要多一些。如果您需要它们,则必须添加它们。这应该足以将您的bson 数据输出为csv。
我已将支持函数放在一个类中以支持流式传输到任何std::ostream。
bson_csv_adapter.hpp
#ifndef BSON_CSV_ADAPTER_HPP_IUPAHOIUHASDUIKHLKHAD
#define BSON_CSV_ADAPTER_HPP_IUPAHOIUHASDUIKHLKHAD
#include <bsoncxx/types.hpp>
#include <ostream>
class BsonCSVadapter {
public:
// construct from a bsoncxx::document::view
explicit BsonCSVadapter(bsoncxx::document::view&& bdv) : m_bdv(std::move(bdv)) {}
std::ostream& print(std::ostream& os) const {
print_view(os, m_bdv);
return os << '\n';
}
private:
void print_view(std::ostream& os, const bsoncxx::document::view& v) const {
print_range(os, v.begin(), v.end());
}
template<typename It>
void print_range(std::ostream& os, It begin, It end) const {
if(begin != end) {
print_element(os, *begin);
for(++begin; begin != end; ++begin) {
os << ',';
print_element(os, *begin);
}
}
}
// bsoncxx::document::element or bsoncxx::array::element
template<typename ElType>
void print_element(std::ostream& os, const ElType& e) const {
// os << e.key().to_string() << ':'; // if you want the fields key name
switch(e.type()) { // bsoncxx::type
case bsoncxx::type::k_double:
os << e.get_double();
break;
case bsoncxx::type::k_int32:
os << e.get_int32();
break;
case bsoncxx::type::k_utf8: {
bsoncxx::stdx::string_view sv = e.get_utf8();
os << sv.data();
break;
}
case bsoncxx::type::k_array: {
const bsoncxx::array::view& av = e.get_array();
print_view(os, av);
break;
}
case bsoncxx::type::k_document: {
const bsoncxx::document::view& dv = e.get_document();
print_view(os, dv);
break;
}
}
}
bsoncxx::document::view m_bdv;
};
// operator to support streaming
std::ostream& operator<<(std::ostream& os, const BsonCSVadapter& a) {
return a.print(os);
}
#endif
然后在您的.cpp 文件中:
#include "bson_csv_adapter.hpp"
// ...
if(maybe_result) {
// stream to std::cout
std::cout << BsonCSVadapter(*maybe_result);
// stream to a file
std::ofstream myfile("newtest.csv");
myfile << BsonCSVadapter(*maybe_result);
}
输出:
5f2a435186ff70fb16f873ec,Gutta,sumanth,25,active,sumanth@gmail.com
如果您取消注释 os << e.key().to_string() << ':'; 行,您将获得以下输出:
_id:$oid:5f2a435186ff70fb16f873ec,first_name:Gutta,last_name:sumanth,age:25,employee_status:active,email:sumanth@gmail.com