我试图用C ++和MongoDB完成一些事情。到目前为止,存在无数问题,但我已经完成了。
然后我得到了这个:
terminate called after throwing an instance of 'mongocxx::v_noabi::logic_error'
what(): invalid use of default constructed or moved-from mongocxx::client object
Aborted
坦率地说,我失去了希望。这是我试图运行的示例:
https://docs.mongodb.com/getting-started/cpp/insert/。
当我尝试运行已编译的程序时出现错误。我能够编译并运行'hellomongo'示例就好了,所以至少部分地,驱动程序安装正确。
我的代码:
#include <chrono>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.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, char**)
{
mongocxx::instance inst{};
mongocxx::client conn{};
auto db = conn["test"];
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::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date { std::chrono::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "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));
}
我使用以下命令编译示例:
c++ --std=c++11 test.cpp -o test $(pkg-config --cflags --libs libmongocxx)
任何帮助表示赞赏!我对C ++的经验很少,所以我对可能出现的问题感到有点迷茫。
答案 0 :(得分:1)
正如acm指出的那样,docs.mongodb.com上的文档已经过时了。 Github的例子工作得很好。我会将此标记为已回答。