MongoDB C++ Driver legacy-1.1.2
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Member Functions | Protected Member Functions | List of all members
mongo::DBClientReplicaSet Class Reference

Use this class to connect to a replica set of servers. More...

#include <dbclient_rs.h>

+ Inheritance diagram for mongo::DBClientReplicaSet:

Classes

class  LazyState
 for storing (non-threadsafe) information between lazy calls More...
 

Public Member Functions

 DBClientReplicaSet (const std::string &name, const std::vector< HostAndPort > &servers, double so_timeout=0)
 Call connect() after constructing.
 
bool connect ()
 Returns false if no member of the set were reachable.
 
virtual void logout (const std::string &dbname, BSONObj &info)
 Logs out the connection for the given database.
 
virtual std::auto_ptr< DBClientCursorquery (const std::string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
 throws userassertion "no master found"
 
virtual BSONObj findOne (const std::string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 throws userassertion "no master found"
 
virtual void insert (const std::string &ns, BSONObj obj, int flags=0, const WriteConcern *wc=NULL)
 insert an object into the database
 
virtual void insert (const std::string &ns, const std::vector< BSONObj > &v, int flags=0, const WriteConcern *wc=NULL)
 insert a vector of objects into the database
 
DBClientConnectionmasterConn ()
 WARNING: this method is very dangerous - this object can decide to free the returned master connection any time.
 
DBClientConnectionslaveConn ()
 WARNING: this method is very dangerous - this object can decide to free the returned master connection any time.
 
bool isStillConnected ()
 if not checked recently, checks whether the underlying socket/sockets are still valid
 
virtual bool call (Message &toSend, Message &response, bool assertOk=true, std::string *actualServer=0)
 actualServer is set to the actual server where they call went if there was a choice (SlaveOk)
 
virtual void reset ()
 Performs a "soft reset" by clearing all states relating to secondary nodes and returning secondary connections to the pool.
 
virtual std::auto_ptr< DBClientCursorquery (const std::string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
 send a query to the database.
 
virtual unsigned long long query (stdx::function< void(const BSONObj &)> f, const std::string &ns, Query query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 Uses QueryOption_Exhaust, when available.
 
virtual void update (const std::string &ns, Query query, BSONObj obj, bool upsert=false, bool multi=false, const WriteConcern *wc=NULL)
 updates objects matching query
 
virtual void remove (const std::string &ns, Query q, bool justOne=0, const WriteConcern *wc=NULL)
 remove matching objects from the database
 
- Public Member Functions inherited from mongo::DBClientBase
virtual std::auto_ptr< DBClientCursorquery (const std::string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
 send a query to the database.
 
virtual void parallelScan (const StringData &ns, int numCursors, std::vector< DBClientCursor * > *cursors, stdx::function< DBClientBase *()> connectionFactory)
 Returns a list of up to 'numCursors' cursors that can be iterated concurrently.
 
virtual unsigned long long query (stdx::function< void(const BSONObj &)> f, const std::string &ns, Query query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 Uses QueryOption_Exhaust, when available.
 
virtual std::auto_ptr< DBClientCursorgetMore (const std::string &ns, long long cursorId, int nToReturn=0, int options=0)
 don't use this - called automatically by DBClientCursor for you
 
virtual void insert (const std::string &ns, BSONObj obj, int flags=0, const WriteConcern *wc=NULL)
 insert an object into the database
 
virtual void insert (const std::string &ns, const std::vector< BSONObj > &v, int flags=0, const WriteConcern *wc=NULL)
 insert a vector of objects into the database
 
virtual void update (const std::string &ns, Query query, BSONObj obj, bool upsert=false, bool multi=false, const WriteConcern *wc=NULL)
 updates objects matching query
 
BSONObj findAndModify (const StringData &ns, const BSONObj &query, const BSONObj &update, bool upsert=false, bool returnNew=false, const BSONObj &sort=BSONObj(), const BSONObj &fields=BSONObj(), const WriteConcern *wc=NULL, bool bypassDocumentValidation=false)
 Modifies and returns a single document.
 
BSONObj findAndRemove (const StringData &ns, const BSONObj &query, const BSONObj &sort=BSONObj(), const BSONObj &fields=BSONObj(), const WriteConcern *wc=NULL)
 Removes and returns a single document.
 
virtual BulkOperationBuilder initializeUnorderedBulkOp (const std::string &ns)
 Initializes an unordered bulk operation by returning an object that can be used to enqueue multiple operations for batch execution.
 
virtual BulkOperationBuilder initializeOrderedBulkOp (const std::string &ns)
 Initializes an ordered bulk operation by returning an object that can be used to enqueue multiple operations for batch execution.
 
virtual void remove (const std::string &ns, Query q, bool justOne=0, const WriteConcern *wc=NULL)
 remove matching objects from the database
 
virtual bool isStillConnected ()=0
 if not checked recently, checks whether the underlying socket/sockets are still valid
 
- Public Member Functions inherited from mongo::DBClientWithCommands
bool simpleCommand (const std::string &dbname, BSONObj *info, const std::string &command)
 helper function.
 
virtual bool runCommand (const std::string &dbname, const BSONObj &cmd, BSONObj &info, int options=0)
 Run a database command.
 
void auth (const BSONObj &params)
 Authenticate a user.
 
bool auth (const std::string &dbname, const std::string &username, const std::string &pwd, std::string &errmsg, bool digestPassword=true)
 Authorize access to a particular database.
 
virtual void logout (const std::string &dbname, BSONObj &info)
 Logs out the connection for the given database.
 
virtual unsigned long long count (const std::string &ns, const Query &query=Query(), int options=0, int limit=0, int skip=0)
 count number of objects in collection ns that match the query criteria specified throws UserAssertion if database returns an error
 
virtual bool isMaster (bool &isMaster, BSONObj *info=0)
 returns true in isMaster parm if this db is the current master of a replica pair.
 
bool createCollection (const std::string &ns, long long size=0, bool capped=false, int max=0, BSONObj *info=0)
 Create a new collection in the database.
 
bool createCollectionWithOptions (const std::string &ns, long long size=0, bool capped=false, int max=0, const BSONObj &extraOptions=BSONObj(), BSONObj *info=0)
 Creates a new collection in the database.
 
std::string getLastError (const std::string &db, bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Get error result from the last write operation (insert/update/delete) on this connection.
 
std::string getLastError (bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Same as the form of getLastError that takes a dbname, but just uses the admin DB.
 
virtual BSONObj getLastErrorDetailed (const std::string &db, bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Get error result from the last write operation (insert/update/delete) on this connection.
 
virtual BSONObj getLastErrorDetailed (bool fsync=false, bool j=false, int w=0, int wtimeout=0)
 Same as the form of getLastErrorDetailed that takes a dbname, but just uses the admin DB.
 
BSONObj getPrevError ()
 Return the last error which has occurred, even if not the very last operation.
 
bool resetError ()
 Reset the previous error state for this connection (accessed via getLastError and getPrevError).
 
virtual bool dropCollection (const std::string &ns, BSONObj *info=NULL)
 Delete the specified collection.
 
bool repairDatabase (const std::string &dbname, BSONObj *info=0)
 Perform a repair and compaction of the specified database.
 
bool copyDatabase (const std::string &fromdb, const std::string &todb, const std::string &fromhost="", const std::string &mechanism="DEFAULT", const std::string &username="", const std::string &password="", BSONObj *info=0)
 Copy database from one server or name to another server or name.
 
BSONObj mapreduce (const std::string &ns, const std::string &jsmapf, const std::string &jsreducef, Query query=Query(), MROutput output=MRInline)
 Run a map/reduce job on the server.
 
void group (const StringData &ns, const StringData &jsreduce, std::vector< BSONObj > *output, const BSONObj &initial=BSONObj(), const Query &query=Query(), const BSONObj &key=BSONObj(), const StringData &finalize="")
 Groups documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums.
 
void groupWithKeyFunction (const StringData &ns, const StringData &jsreduce, std::vector< BSONObj > *output, const BSONObj &initial=BSONObj(), const Query &query=Query(), const StringData &jskey="", const StringData &finalize="")
 Does the same thing as 'group' but accepts a key function, 'jskey', that is used to create an object representing the key.
 
BSONObj distinct (const StringData &ns, const StringData &field, const Query &query=Query())
 Finds the distinct values for a specified field across a single collection and returns the results in an array.
 
bool eval (const std::string &dbname, const std::string &jscode, BSONObj &info, BSONElement &retValue, BSONObj *args=0, bool nolock=false)
 Run javascript code on the database server.
 
bool validate (const std::string &ns, bool scandata=true)
 validate a collection, checking for errors and reporting back statistics.
 
template<class T , class NumType >
 MONGO_CLIENT_DEPRECATED ("deprecated in MongoDB 3.0") bool eval(const std
 eval invocation with one parm to server and one numeric field (either int or double) returned
 
std::list< std::string > getDatabaseNames ()
 get a list of all the current databases uses the { listDatabases : 1 } command.
 
std::list< std::string > getCollectionNames (const std::string &db, const BSONObj &filter=BSONObj())
 Get a list of all the current collections in db.
 
std::list< BSONObjgetCollectionInfos (const std::string &db, const BSONObj &filter=BSONObj())
 { name : "<short collection name>", options : { } }
 
std::auto_ptr< DBClientCursorenumerateCollections (const std::string &db, const BSONObj &filter=BSONObj(), int batchSize=0)
 Returns a DBClientCursor with collection information objects.
 
void createIndex (const StringData &ns, const BSONObj &keys)
 Create an index on the collection 'ns' as described by the given keys.
 
virtual void createIndex (const StringData &ns, const IndexSpec &descriptor)
 Create an index on the collection 'ns' as described by the given descriptor.
 
virtual std::list< std::string > getIndexNames (const std::string &ns, int options=0)
 Enumerates all indexes on ns (a db-qualified collection name).
 
virtual void dropIndexes (const std::string &ns)
 drops all indexes for the collection
 
virtual bool dropDatabase (const std::string &dbname, BSONObj *info=0)
 Erase / drop an entire database.
 
- Public Member Functions inherited from mongo::DBClientInterface
virtual BSONObj findOne (const std::string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 
void findN (std::vector< BSONObj > &out, const std::string &ns, Query query, int nToReturn, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
 query N objects from the database into an array.
 
void save (const StringData &ns, const BSONObj &toSave, const WriteConcern *wc=NULL)
 Saves a document to a collection.
 
virtual std::auto_ptr< DBClientCursorgetMore (const std::string &ns, long long cursorId, int nToReturn=0, int options=0)=0
 don't use this - called automatically by DBClientCursor for you
 
virtual bool call (Message &toSend, Message &response, bool assertOk=true, std::string *actualServer=0)=0
 actualServer is set to the actual server where they call went if there was a choice (SlaveOk)
 

Static Public Member Functions

static bool MONGO_CLIENT_FUNC isSecondaryQuery (const std::string &ns, const BSONObj &queryObj, int queryOptions)
 Returns whether a query or command can be sent to secondaries based on the query object and options.
 
static void setAuthPooledSecondaryConn (bool setting)
 @bool setting if true, DBClientReplicaSet connections will make sure that secondary connections are authenticated and log them before returning them to the pool.
 
- Static Public Member Functions inherited from mongo::DBClientWithCommands
static std::string MONGO_CLIENT_FUNC getLastErrorString (const BSONObj &res)
 Can be called with the returned value from getLastErrorDetailed to extract an error string.
 

Protected Member Functions

virtual void _auth (const BSONObj &params)
 Authorize.
 
- Protected Member Functions inherited from mongo::DBClientWithCommands
bool isOk (const BSONObj &)
 if the result of a command is ok
 
bool isNotMasterErrorString (const BSONElement &e)
 if the element contains a not master error
 
QueryOptions availableOptions ()
 Look up the options available on this client.
 
bool _authMongoCR (const std::string &dbname, const std::string &username, const std::string &pwd, BSONObj *info, bool digestPassword)
 Use the MONGODB-CR protocol to authenticate as "username" against the database "dbname", with the given password.
 
bool _authX509 (const std::string &dbname, const std::string &username, BSONObj *info)
 Use the MONGODB-X509 protocol to authenticate as "username.
 

Additional Inherited Members

- Public Types inherited from mongo::DBClientWithCommands
enum  ProfilingLevel
 The Mongo database provides built-in performance profiling capabilities. More...
 
typedef stdx::function< void(BSONObjBuilder *)> RunCommandHookFunc
 A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns nothing.
 
typedef stdx::function< void(const BSONObj &, const std::string &)> PostRunCommandHookFunc
 Similar to above, but for running a function on a command response after a command has been run.
 
- Public Attributes inherited from mongo::DBClientWithCommands
logger::LogSeverity _logLevel
 controls how chatty the client is about network errors & such.
 
- Protected Attributes inherited from mongo::DBClientWithCommands
RunCommandHookFunc _runCommandHook
 These functions will be executed by the driver on runCommand calls.
 

Detailed Description

Use this class to connect to a replica set of servers.

The class will manage checking for which server in a replica set is master, and do failover automatically.

This can also be used to connect to replica pairs since pairs are a subset of sets

On a failover situation, expect at least one operation to return an error (throw an exception) before the failover is complete. Operations are not retried.

Constructor & Destructor Documentation

◆ DBClientReplicaSet()

mongo::DBClientReplicaSet::DBClientReplicaSet ( const std::string &  name,
const std::vector< HostAndPort > &  servers,
double  so_timeout = 0 
)

Call connect() after constructing.

autoReconnect is always on for DBClientReplicaSet connections.

Member Function Documentation

◆ _auth()

virtual void mongo::DBClientReplicaSet::_auth ( const BSONObj params)
protectedvirtual

Authorize.

Authorizes all nodes as needed

Reimplemented from mongo::DBClientWithCommands.

◆ connect()

bool mongo::DBClientReplicaSet::connect ( )

Returns false if no member of the set were reachable.

This object can still be used even when false was returned as it will try to reconnect when you use it later.

◆ isSecondaryQuery()

static bool MONGO_CLIENT_FUNC mongo::DBClientReplicaSet::isSecondaryQuery ( const std::string &  ns,
const BSONObj queryObj,
int  queryOptions 
)
static

Returns whether a query or command can be sent to secondaries based on the query object and options.

Parameters
nsthe namespace of the query.
queryObjthe query object to check.
queryOptionsthe query options
Returns
true if the query/cmd could potentially be sent to a secondary, false otherwise

◆ logout()

virtual void mongo::DBClientReplicaSet::logout ( const std::string &  dbname,
BSONObj info 
)
virtual

Logs out the connection for the given database.

Parameters
dbnamethe database to logout from.
infothe result object for the logout command (provided for backwards compatibility with mongo shell)

Reimplemented from mongo::DBClientWithCommands.

◆ masterConn()

DBClientConnection & mongo::DBClientReplicaSet::masterConn ( )

WARNING: this method is very dangerous - this object can decide to free the returned master connection any time.

Returns
the reference to the address that points to the master connection.

◆ query() [1/2]

virtual std::auto_ptr< DBClientCursor > mongo::DBClientBase::query ( const std::string &  ns,
Query  query,
int  nToReturn = 0,
int  nToSkip = 0,
const BSONObj fieldsToReturn = 0,
int  queryOptions = 0,
int  batchSize = 0 
)
virtual

send a query to the database.

Parameters
nsnamespace to query, format is <dbname>.<collectname>[.<collectname>]*
queryquery to perform on the collection. this is a BSONObj (binary JSON) You may format as { query: { ... }, orderby: { ... } } to specify a sort order.
nToReturnn to return (i.e., limit). 0 = unlimited
nToSkipstart with the nth item
fieldsToReturnoptional template of which fields to select. if unspecified, returns all fields
queryOptionssee options enum at top of this file
Returns
cursor. 0 if error (connection failure)
Exceptions
AssertionException

Reimplemented from mongo::DBClientBase.

◆ query() [2/2]

virtual unsigned long long mongo::DBClientBase::query ( stdx::function< void(const BSONObj &)>  f,
const std::string &  ns,
Query  query,
const BSONObj fieldsToReturn = 0,
int  queryOptions = 0 
)
virtual

Uses QueryOption_Exhaust, when available.

Exhaust mode sends back all data queries as fast as possible, with no back-and-forth for OP_GETMORE. If you are certain you will exhaust the query, it could be useful.

Use the DBClientCursorBatchIterator version, below, if you want to do items in large blocks, perhaps to avoid granular locking and such.

Reimplemented from mongo::DBClientBase.

◆ remove()

virtual void mongo::DBClientBase::remove ( const std::string &  ns,
Query  q,
bool  justOne = 0,
const WriteConcern wc = NULL 
)
virtual

remove matching objects from the database

Parameters
justOneif this true, then once a single match is found will stop

Reimplemented from mongo::DBClientBase.

◆ slaveConn()

DBClientConnection & mongo::DBClientReplicaSet::slaveConn ( )

WARNING: this method is very dangerous - this object can decide to free the returned master connection any time.

This can also unpin the cached slaveOk/read preference connection.

Returns
the reference to the address that points to a secondary connection.

The documentation for this class was generated from the following file: