Details
-
Task
-
Resolution: Done
-
Critical - P2
-
None
-
3.0.0
-
None
-
ubuntu 16.04 lts, gcc 5.4.0
Description
I want to wrap mongocxx::client in some class.
I wrote this class:
|
MongoDbConnection.h |
|
|
class MongoDbConnection
|
{
|
public:
|
explicit MongoDbConnection(const std::string& dbName) :
|
dbName(dbName)
|
,instance()
|
,connection()
|
{
|
}
|
~MongoDbConnection()
|
{
|
}
|
|
|
void connect(const std::string& host)
|
{
|
if (connection)
|
{
|
return;
|
}
|
|
mongocxx::uri uri(host);
|
connection = std::move(mongocxx::client(uri));
|
}
|
DatabaseCursor findWithCursor(const std::string& collectionName, const view_or_value& query)
|
{
|
if (isConnectionOk())
|
{
|
mongocxx::collection collection = connection
|
.database(dbName)
|
.collection(collectionName);
|
mongocxx::cursor cursor = collection.find(query);
|
return DatabaseCursor(cursor);
|
}
|
DatabaseCursor dbCursor;
|
return dbCursor;
|
}
|
|
|
private:
|
bool isConnectionOk() const
|
{
|
const bool res = (bool)connection;
|
return res;
|
}
|
|
|
const std::string dbName;
|
mongocxx::instance instance;
|
mongocxx::client connection;
|
};
|
And class which contains mongocxx::cursor
|
DatabaseCursor.h |
class DatabaseCursor
|
{
|
public:
|
DatabaseCursor() :
|
current(nullptr)
|
,end(nullptr)
|
,_isNull(true)
|
{
|
std::cout << "DatabaseCursor::DatabaseCursor() :" << std::endl;
|
}
|
DatabaseCursor(mongocxx::cursor& cursor) :
|
current(new mongocxx::cursor::iterator(cursor.begin()))
|
,end(new mongocxx::cursor::iterator(cursor.end()))
|
,_isNull(current == end)
|
{
|
std::cout << "DatabaseCursor::DatabaseCursor(mongocxx::cursor& cursor) :" << std::endl;
|
}
|
DatabaseCursor(DatabaseCursor&& cursor) :
|
current(std::move(cursor.current))
|
,end(std::move(cursor.end))
|
,_isNull(std::move(cursor._isNull))
|
{
|
std::cout << "DatabaseCursor::DatabaseCursor(DatabaseCursor&& cursor) :" << std::endl;
|
}
|
|
|
DatabaseCursor(const DatabaseCursor& other) = delete;
|
DatabaseCursor& operator =(const DatabaseCursor& other) = delete;
|
|
|
bool next(bsoncxx::document::value& obj)
|
{
|
if (!current || !end || (*current) == (*end))
|
{
|
return false;
|
}
|
mongocxx::cursor::iterator iter = (*current);
|
bsoncxx::document::view_or_value doc(*iter);
|
obj = bsoncxx::document::value(doc.view());
|
// ++(*current);
|
try
|
{
|
++iter;
|
}
|
catch (mongocxx::query_exception& e)
|
{
|
std::cout << e.what() << std::endl;
|
}
|
|
|
current.reset(new mongocxx::cursor::iterator(iter));
|
|
|
return true;
|
}
|
bool isNull() const
|
{
|
return _isNull;
|
}
|
|
|
private:
|
std::unique_ptr<mongocxx::cursor::iterator> current, end;
|
bool _isNull;
|
};
|