1。C 语言登录mongodb,解决登录失败错误:Authentication failed.: mongoc client_authenticate error
代码如下:
-
#include <bson.h>
-
#include <bcon.h>
-
#include <mongoc.h>
-
-
int main (int argc,
-
char *argv[])
-
{
-
mongoc_client_t *client;
-
mongoc_database_t *database;
-
mongoc_collection_t *collection;
-
bson_t *command, reply, *insert;
-
bson_error_t error;
-
char *str;
-
bool retval;
-
-
-
mongoc_init ();
-
client = mongoc_client_new("mongodb://mydbUser:aaaaaa@localhost:27017/?authSource=mydb");
-
database = mongoc_client_get_database (client, "mydb");
-
collection = mongoc_client_get_collection (client, "mydb", "student");
-
command = BCON_NEW ("ping", BCON_INT32 (1));
-
retval = mongoc_client_command_simple (client, "mydbUser", command, NULL, &reply, &error);
-
if (!retval) {
-
fprintf (stderr, "%s\n", error.message);
-
return EXIT_FAILURE;
-
}
-
str = bson_as_json (&reply, NULL);
-
printf ("%s\n", str);
-
insert = BCON_NEW ("hello", BCON_UTF8 ("world"));
-
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, insert, NULL, &error)) {
-
fprintf (stderr, "%s\n", error.message);
-
}
-
bson_destroy (insert);
-
bson_destroy (&reply);
-
bson_destroy (command);
-
bson_free (str);
-
-
mongoc_collection_destroy (collection);
-
mongoc_database_destroy (database);
-
mongoc_client_destroy (client);
-
mongoc_cleanup ();
-
-
return 0;
-
}
代码中第18行是登录关键:
-
client = mongoc_client_new("mongodb://mydbUser:aaaaaa@localhost:27017/?authSource=mydb")
容易看出登录是已uri格式登录的,并可划分成几部分
:
-
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
开始我的登录出错是因为uri格式不对,错误提示:
-
what(): Authentication failed.: mongoc client_authenticate error
2。C++ 登录mongodb
代码如下:
-
#include <iostream>
-
-
#include <bsoncxx/builder/stream/document.hpp>
-
#include <bsoncxx/json.hpp>
-
-
#include <mongocxx/client.hpp>
-
#include <mongocxx/instance.hpp>
-
-
int main(int, char**) {
-
mongocxx::instance inst{};
-
mongocxx::client conn{mongocxx::uri{"mongodb://mydbUser:aaaaaa@localhost:27017/?authSource=mydb"}};
-
-
bsoncxx::builder::stream::document document{};
-
-
auto collection = conn["mydb"]["student"];
-
document << "hai!!!" << "world!!!";
-
-
collection.insert_one(document.view());
-
auto cursor = collection.find({});
-
-
for (auto&& doc : cursor) {
-
std::cout << bsoncxx::to_json(doc) << std::endl;
-
}
-
}
登录成功关键代码是第11行:
-
mongocxx::client conn{mongocxx::uri{"mongodb://mydbUser:aaaaaa@localhost:27017/?authSource=mydb"}}
说明同C 语言!!
参考链接:
C语言参考:
C语言参考2:
C++参考:(New-Driver)
登录细节参考:
登录细节参考2: http://api.mongodb.org/c/current/authentication.html
阅读(5744) | 评论(0) | 转发(0) |