Windows 7,msys2,编译器MinGW
尝试从C ++代码连接到MongoDB实例。使用下一个命令运行mongod
:
mongod --dbpath ./dev-db --bind_ip 127.0.0.1 --port 27017
我通常可以通过mongo
和Robomongo连接到此数据库。
对于c ++代码,我成功编译并安装了最后一个稳定的Mongo C ++驱动程序。我从官方tutorial获取的代码:
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
mongocxx::uri uri("mongodb://127.0.0.1:27017");
mongocxx::client conn{uri};
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::milliseconds{12323}} << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
auto res = db["restaurants"].insert_one(std::move(restaurant_doc))
这提供了下一个错误:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'mongocxx::v_noabi::bulk_write_exception'
what(): No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '127.0.0.1']: generic server error
如何避免此问题并连接到数据库?
答案 0 :(得分:2)
您的副本缺少示例的第一行:
mongocxx::instance inst{};
见http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/#make-a-connection。 mongocxx::instance
构造函数和析构函数分别初始化和关闭驱动程序,因此在使用驱动程序之前必须创建mongocxx::instance
,并且只要驱动程序正在使用中,就必须保持活动状态。
答案 1 :(得分:1)
看起来它正在尝试DNS查找127.0.0.1。尝试将其更改为localhost
(将解析为相同的IP)
mongocxx::uri uri("mongodb://localhost:27017");