2

我试图用 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++ 的经验很少,所以我对可能出现的问题有点迷茫。

4

1 回答 1

1

正如 acm 指出的那样,docs.mongodb.com 上的文档已经过时了。Github 示例运行良好。我会将其标记为已回答。

于 2016-08-11T09:22:56.733 回答