rabbitfoot530's diary

読んだ本と、プログラムに関することのメモです。好きな言語は、C++, Python, Golang, TypeScript。数学・物理・学習理論も好きです。

C++からMongo認証とレプリカセットのMongoを使う!

C++Driverは、各所に手順があるから、そっちに任せるとして、
Driverを入れてからの使い方。

  • MongoDBの認証接続

Mongoに認証の設定してる場合の接続方法

  std::string error_msg;
  const std::string repl = "repl_name/host1:27017,host2:27017,host3:27017"
  mongo::ConnectionString cs = mongo::ConnectionString::parse(repl, error_msg);
  mongo::DBClientReplicaSet* conn_ = static_cast<mongo::DBClientReplicaSet *>(cs.connect(error_msg));
  std::string db_; // use this when insert, update...etc
  const std::string dbname = "db";
  const std::string username = "user1";
  const std::string password = "pass1"
  conn_->auth(dbname, username, password, errmsg);
  • 検索

文字列を見つけて返す

  std::string sid = "buanbONUFOUhsaufaOEruhnHNTudghcaoudahsnXnuZtouh";
  const std::string ns = db_ + "." + collection_;
  mongo::BSONObj res = conn_->findOne(ns, mongo::BSONObjBuilder().append("sessionid", sid.c_str()).obj());

  return res.getStringField(field.c_str());
  • 挿入
  const std::string msg = "hello world ;D";
  mongo::BSONObjBuilder builder;
  // UTCでの時間を挿入する。Mongo Driverが要求してくる時間の型に合わせるのに、Mongoが内部で使ってるmongo::jsTime()を呼び出してる。
  builder.appendDate("time", mongo::jsTime());
  builder.append("msg", msg);
  const std::string ns = db_ + "." + collection_;
  conn_->insert(ns, builder.obj());
  • 更新
  std::string keys = "key1,key2";
  std::string values = "value1,value2";
  std::string sid = "buanbONUFOUhsaufaOEruhnHNTudghcaoudahsnXnuZtouh";
  mongo::Query query(BSON("sid" << sid));
  // queryで指定した項目に対して、値を更新する。
  mongo::BSONObj modifier = BSON("$set" << BSON("keys" << keys << "values" << values));
  
  const std::string ns = db_ + "." + collection_;
  conn_->update(ns, query, modifier, true, true);
  // 第4引数:upsert, 第5引数:multi
  • 削除
  const std::string ns = db_ + "." + collection_;
  conn_->dropCollection(ns);