Created
September 2, 2014 14:13
-
-
Save amidvidy/768834542609ae064fb5 to your computer and use it in GitHub Desktop.
C++ driver example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include <list> | |
#include "mongo/client/dbclient.h" | |
#include "mongo/bson/bson.h" | |
namespace bson { | |
typedef mongo::BSONElement Element; | |
typedef mongo::BSONObj Obj; | |
typedef mongo::BSONObjBuilder Builder; | |
} | |
class CappedCollectionExample { | |
public: | |
CappedCollectionExample(const std::string& host) { | |
_conn.connect(host); | |
} | |
const bson::Obj getCollectionInfo(const std::string& db, const std::string& name) { | |
const std::list<bson::Obj> collections = _conn.getCollectionInfos(db); | |
for (std::list<bson::Obj>::const_iterator it = collections.begin(); | |
it != collections.end(); | |
++it) { | |
bson::Obj col(*it); | |
if (col["name"].str() == name) { | |
return col; | |
} | |
} | |
return bson::Obj(); | |
} | |
bool isCapped(const bson::Obj& col) { | |
return col.hasField("options") && | |
col["options"].Obj().hasField("capped") && | |
col["options"].Obj()["capped"].Bool(); | |
} | |
// returns true if collection was dropped | |
bool drop(const std::string& db, const std::string& name) { | |
return _conn.dropCollection(makeNs(db, name)); | |
} | |
// Drops collection if it already exists | |
bool createCappedCollection(const std::string& db, const std::string& name, std::size_t size) { | |
return _conn.createCollection(makeNs(db, name), size, true); | |
} | |
bool insertIntoCapped(const std::string& db, const std::string& name, const bson::Obj& obj) { | |
_conn.insert(db + "." + name, obj); | |
return true; | |
} | |
private: | |
std::string makeNs(const std::string& db, const std::string col) { | |
return db + "." + col; | |
} | |
mongo::DBClientConnection _conn; | |
}; | |
namespace { | |
const std::string DB = "test"; | |
const std::string COLL = "capped_example"; | |
const std::size_t SIZE = 1000; | |
} | |
int main(int argc, char** argv) { | |
try { | |
CappedCollectionExample cc("localhost"); | |
const bson::Obj col = cc.getCollectionInfo(DB, COLL); | |
if (col.isEmpty()) { | |
cc.createCappedCollection(DB, COLL, SIZE); | |
} else if (!cc.isCapped(col)) { | |
cc.drop(DB, COLL); | |
cc.createCappedCollection(DB, COLL, SIZE); | |
} | |
cc.insertIntoCapped(DB, COLL, bson::Builder().append("hello", "world").obj()); | |
} catch (const mongo::DBException &ex) { | |
std::cout << "caught " << ex.what() << std::endl; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment