MongoDB  2.7.0
Classes | Public Types | Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | Protected Member Functions | Protected Attributes | List of all members
mongo::DBClientWithCommands Class Referenceabstract

DB "commands" Basically just invocations of connection. More...

#include <dbclientinterface.h>

Inheritance diagram for mongo::DBClientWithCommands:
mongo::DBClientInterface mongo::DBClientBase mongo::DBClientConnection mongo::DBClientReplicaSet mongo::SyncClusterConnection

Classes

struct  MROutput
 This implicitly converts from char*, string, and BSONObj to be an argument to mapreduce You shouldn't need to explicitly construct this. More...
 

Public Types

enum  ProfilingLevel { ProfileOff = 0, ProfileSlow = 1, ProfileAll = 2 }
 The Mongo database provides built-in performance profiling capabilities. More...
 
typedef boost::function< void(BSONObjBuilder *)> RunCommandHookFunc
 A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns nothing. More...
 
typedef boost::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 Member Functions

bool simpleCommand (const string &dbname, BSONObj *info, const string &command)
 helper function. More...
 
virtual bool runCommand (const string &dbname, const BSONObj &cmd, BSONObj &info, int options=0)
 Run a database command. More...
 
void auth (const BSONObj &params)
 Authenticate a user. More...
 
bool auth (const string &dbname, const string &username, const string &pwd, string &errmsg, bool digestPassword=true)
 Authorize access to a particular database. More...
 
virtual void logout (const string &dbname, BSONObj &info)
 Logs out the connection for the given database. More...
 
virtual unsigned long long count (const string &ns, const BSONObj &query=BSONObj(), 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. More...
 
bool createCollection (const string &ns, long long size=0, bool capped=false, int max=0, BSONObj *info=0)
 Create a new collection in the database. More...
 
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. More...
 
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. More...
 
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. More...
 
bool resetError ()
 Reset the previous error state for this connection (accessed via getLastError and getPrevError). More...
 
virtual bool dropCollection (const string &ns, BSONObj *info=NULL)
 Delete the specified collection. More...
 
bool repairDatabase (const string &dbname, BSONObj *info=0)
 Perform a repair and compaction of the specified database. More...
 
bool copyDatabase (const string &fromdb, const string &todb, const string &fromhost="", BSONObj *info=0)
 Copy database from one server or name to another server or name. More...
 
bool setDbProfilingLevel (const string &dbname, ProfilingLevel level, BSONObj *info=0)
 
bool getDbProfilingLevel (const string &dbname, ProfilingLevel &level, BSONObj *info=0)
 
BSONObj mapreduce (const string &ns, const string &jsmapf, const string &jsreducef, BSONObj query=BSONObj(), MROutput output=MRInline)
 Run a map/reduce job on the server. More...
 
bool eval (const string &dbname, const string &jscode, BSONObj &info, BSONElement &retValue, BSONObj *args=0)
 Run javascript code on the database server. More...
 
bool validate (const string &ns, bool scandata=true)
 validate a collection, checking for errors and reporting back statistics. More...
 
bool eval (const string &dbname, const string &jscode)
 
template<class T >
bool eval (const string &dbname, const string &jscode, T parm1)
 
template<class T , class NumType >
bool eval (const string &dbname, const string &jscode, T parm1, NumType &ret)
 eval invocation with one parm to server and one numeric field (either int or double) returned
 
list< string > getDatabaseNames ()
 get a list of all the current databases uses the { listDatabases : 1 } command. More...
 
list< string > getCollectionNames (const string &db)
 get a list of all the current collections in db
 
bool exists (const string &ns)
 
virtual bool ensureIndex (const string &ns, BSONObj keys, bool unique=false, const string &name="", bool cache=true, bool background=false, int v=-1, int ttl=0)
 Create an index if it does not already exist. More...
 
virtual void resetIndexCache ()
 clears the index cache, so the subsequent call to ensureIndex for any index will go to the server
 
virtual auto_ptr< DBClientCursorgetIndexes (const string &ns)
 
virtual void dropIndex (const string &ns, BSONObj keys)
 
virtual void dropIndex (const string &ns, const string &indexName)
 
virtual void dropIndexes (const string &ns)
 drops all indexes for the collection
 
virtual void reIndex (const string &ns)
 
string genIndexName (const BSONObj &keys)
 
virtual bool dropDatabase (const string &dbname, BSONObj *info=0)
 Erase / drop an entire database.
 
virtual string toString () const =0
 
virtual void setRunCommandHook (RunCommandHookFunc func)
 
RunCommandHookFunc getRunCommandHook () const
 
virtual void setPostRunCommandHook (PostRunCommandHookFunc func)
 
PostRunCommandHookFunc getPostRunCommandHook () const
 
- Public Member Functions inherited from mongo::DBClientInterface
virtual auto_ptr< DBClientCursorquery (const string &ns, Query query, int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)=0
 
virtual void insert (const string &ns, BSONObj obj, int flags=0)=0
 
virtual void insert (const string &ns, const vector< BSONObj > &v, int flags=0)=0
 
virtual void remove (const string &ns, Query query, bool justOne=0)=0
 
virtual void remove (const string &ns, Query query, int flags)=0
 
virtual void update (const string &ns, Query query, BSONObj obj, bool upsert=false, bool multi=false)=0
 
virtual void update (const string &ns, Query query, BSONObj obj, int flags)=0
 
virtual BSONObj findOne (const string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 
void findN (vector< BSONObj > &out, const string &ns, Query query, int nToReturn, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0)
 query N objects from the database into an array. More...
 
virtual string getServerAddress () const =0
 
virtual auto_ptr< DBClientCursorgetMore (const string &ns, long long cursorId, int nToReturn=0, int options=0)=0
 don't use this - called automatically by DBClientCursor for you
 

Static Public Member Functions

static string createPasswordDigest (const string &username, const string &clearTextPassword)
 
static string getLastErrorString (const BSONObj &res)
 Can be called with the returned value from getLastErrorDetailed to extract an error string. More...
 

Public Attributes

logger::LogSeverity _logLevel
 controls how chatty the client is about network errors & such. More...
 

Static Public Attributes

static MROutput MRInline
 

Protected Member Functions

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
 
BSONObj _countCmd (const string &ns, const BSONObj &query, int options, int limit, int skip)
 
QueryOptions availableOptions ()
 Look up the options available on this client. More...
 
virtual QueryOptions _lookupAvailableOptions ()
 
virtual void _auth (const BSONObj &params)
 
bool _authMongoCR (const string &dbname, const string &username, const string &pwd, BSONObj *info, bool digestPassword)
 Use the MONGODB-CR protocol to authenticate as "username" against the database "dbname", with the given password. More...
 
bool _authX509 (const string &dbname, const string &username, BSONObj *info)
 Use the MONGODB-X509 protocol to authenticate as "username. More...
 

Protected Attributes

RunCommandHookFunc _runCommandHook
 These functions will be executed by the driver on runCommand calls.
 
PostRunCommandHookFunc _postRunCommandHook
 

Detailed Description

DB "commands" Basically just invocations of connection.

$cmd.findOne({...});

Member Typedef Documentation

A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns nothing.

The builder contains a runCommand BSON object. Once such a function is set as the runCommand hook, every time the DBClient processes a runCommand, the hook will be called just prior to sending it to the server.

Member Enumeration Documentation

The Mongo database provides built-in performance profiling capabilities.

Uset setDbProfilingLevel() to enable. Profiling information is then written to the system.profile collection, which one can then query.

Member Function Documentation

bool mongo::DBClientWithCommands::_authMongoCR ( const string &  dbname,
const string &  username,
const string &  pwd,
BSONObj info,
bool  digestPassword 
)
protected

Use the MONGODB-CR protocol to authenticate as "username" against the database "dbname", with the given password.

If digestPassword is false, the password is assumed to be pre-digested. Returns false on failure, and sets "errmsg".

bool mongo::DBClientWithCommands::_authX509 ( const string &  dbname,
const string &  username,
BSONObj info 
)
protected

Use the MONGODB-X509 protocol to authenticate as "username.

The certificate details has already been communicated automatically as part of the connect call. Returns false on failure and set "errmsg".

void mongo::DBClientWithCommands::auth ( const BSONObj params)

Authenticate a user.

The "params" BSONObj should be initialized with some of the fields below. Which fields are required depends on the mechanism, which is mandatory.

"mechanism": The string name of the sasl mechanism to use.  Mandatory.
"user": The string name of the user to authenticate.  Mandatory.
"db": The database target of the auth command, which identifies the location
    of the credential information for the user.  May be "$external" if
    credential information is stored outside of the mongo cluster.  Mandatory.
"pwd": The password data.
"digestPassword": Boolean, set to true if the "pwd" is undigested (default).
"serviceName": The GSSAPI service name to use.  Defaults to "mongodb".
"serviceHostname": The GSSAPI hostname to use.  Defaults to the name of the remote
     host.

Other fields in "params" are silently ignored.

Returns normally on success, and throws on error. Throws a DBException with getCode() == ErrorCodes::AuthenticationFailed if authentication is rejected. All other exceptions are tantamount to authentication failure, but may also indicate more serious problems.

bool mongo::DBClientWithCommands::auth ( const string &  dbname,
const string &  username,
const string &  pwd,
string &  errmsg,
bool  digestPassword = true 
)

Authorize access to a particular database.

Authentication is separate for each database on the server – you may authenticate for any number of databases on a single connection. The "admin" database is special and once authenticated provides access to all databases on the server.

Parameters
digestPasswordif password is plain text, set this to true. otherwise assumed to be pre-digested
[out]authLevellevel of authentication for the given user
Returns
true if successful
enum QueryOptions mongo::DBClientWithCommands::availableOptions ( )
protected

Look up the options available on this client.

Caches the answer from _lookupAvailableOptions(), below.

bool mongo::DBClientWithCommands::copyDatabase ( const string &  fromdb,
const string &  todb,
const string &  fromhost = "",
BSONObj info = 0 
)

Copy database from one server or name to another server or name.

Generally, you should dropDatabase() first as otherwise the copied information will MERGE into whatever data is already present in this database.

For security reasons this function only works when you are authorized to access the "admin" db. However, if you have access to said db, you can copy any database from one place to another. TODO: this needs enhancement to be more flexible in terms of security.

This method provides a way to "rename" a database by copying it to a new db name and location. The copy is "repaired" and compacted.

fromdb database name from which to copy. todb database name to copy to. fromhost hostname of the database (and optionally, ":port") from which to copy the data. copies from self if "".

returns true if successful

bool mongo::DBClientWithCommands::createCollection ( const string &  ns,
long long  size = 0,
bool  capped = false,
int  max = 0,
BSONObj info = 0 
)

Create a new collection in the database.

Normally, collection creation is automatic. You would use this function if you wish to specify special options on creation.

If the collection already exists, no action occurs.

Parameters
nsfully qualified collection name
sizedesired initial extent size for the collection. Must be <= 1000000000 for normal collections. For fixed size (capped) collections, this size is the total/max size of the collection.
cappedif true, this is a fixed size collection (where old data rolls out).
maxmaximum number of objects if capped (optional).

returns true if successful.

virtual bool mongo::DBClientWithCommands::dropCollection ( const string &  ns,
BSONObj info = NULL 
)
inlinevirtual

Delete the specified collection.

Parameters
infoAn optional output parameter that receives the result object the database returns from the drop command. May be null if the caller doesn't need that info.
bool mongo::DBClientWithCommands::ensureIndex ( const string &  ns,
BSONObj  keys,
bool  unique = false,
const string &  name = "",
bool  cache = true,
bool  background = false,
int  v = -1,
int  ttl = 0 
)
virtual

Create an index if it does not already exist.

ensureIndex calls are remembered so it is safe/fast to call this function many times in your code.

Parameters
nscollection to be indexed
keysthe "key pattern" for the index. e.g., { name : 1 }
uniqueif true, indicates that key uniqueness should be enforced for this index
nameif not specified, it will be created from the keys automatically (which is recommended)
cacheif set to false, the index cache for the connection won't remember this call
backgroundbuild index in the background (see mongodb docs for details)
vindex version. leave at default value. (unit tests set this parameter.)
ttl.The value of how many seconds before data should be removed from a collection.
Returns
whether or not sent message to db. should be true on first call, false on subsequent unless resetIndexCache was called
bool mongo::DBClientWithCommands::eval ( const string &  dbname,
const string &  jscode,
BSONObj info,
BSONElement retValue,
BSONObj args = 0 
)

Run javascript code on the database server.

dbname database SavedContext in which the code runs. The javascript variable 'db' will be assigned to this database when the function is invoked. jscode source code for a javascript function. info the command object which contains any information on the invocation result including the return value and other information. If an error occurs running the jscode, error information will be in info. (try "out() << info.toString()") retValue return value from the jscode function. args args to pass to the jscode function. when invoked, the 'args' variable will be defined for use by the jscode.

returns true if runs ok.

See testDbEval() in dbclient.cpp for an example of usage.

list< string > mongo::DBClientWithCommands::getDatabaseNames ( )

get a list of all the current databases uses the { listDatabases : 1 } command.

throws on error

string mongo::DBClientWithCommands::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.

db doesn't change the command's behavior - it is just for auth checks.

Returns
error message text, or empty string if no error.
BSONObj mongo::DBClientWithCommands::getLastErrorDetailed ( const std::string &  db,
bool  fsync = false,
bool  j = false,
int  w = 0,
int  wtimeout = 0 
)
virtual

Get error result from the last write operation (insert/update/delete) on this connection.

db doesn't change the command's behavior - it is just for auth checks.

Returns
full error object.

If "w" is -1, wait for propagation to majority of nodes. If "wtimeout" is 0, the operation will block indefinitely if needed.

Reimplemented in mongo::SyncClusterConnection.

string mongo::DBClientWithCommands::getLastErrorString ( const BSONObj res)
static

Can be called with the returned value from getLastErrorDetailed to extract an error string.

If all you need is the string, just call getLastError() instead.

BSONObj mongo::DBClientWithCommands::getPrevError ( )

Return the last error which has occurred, even if not the very last operation.

Returns
{ err : <error message>="">, nPrev : <how_many_ops_back_occurred>, ok : 1 }

result.err will be null if no error has occurred.

bool mongo::DBClientWithCommands::isMaster ( bool &  isMaster,
BSONObj info = 0 
)
virtual

returns true in isMaster parm if this db is the current master of a replica pair.

pass in info for more details e.g.: { "ismaster" : 1.0 , "msg" : "not paired" , "ok" : 1.0 }

returns true if command invoked successfully.

void mongo::DBClientWithCommands::logout ( const 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 in mongo::DBClientConnection, and mongo::DBClientReplicaSet.

BSONObj mongo::DBClientWithCommands::mapreduce ( const string &  ns,
const string &  jsmapf,
const string &  jsreducef,
BSONObj  query = BSONObj(),
MROutput  output = MRInline 
)

Run a map/reduce job on the server.

See http://dochub.mongodb.org/core/mapreduce

ns namespace (db+collection name) of input data jsmapf javascript map function code jsreducef javascript reduce function code. query optional query filter for the input output either a string collection name or an object representing output type if not specified uses inline output type

returns a result object which contains: { result : <collection_name>, numObjects : <number_of_objects_scanned>, timeMillis : <job_time>, ok : <1_if_ok>, [, err : <errmsg_if_error>] }

For example one might call: result.getField("ok").trueValue() on the result to check if ok.

bool mongo::DBClientWithCommands::repairDatabase ( const string &  dbname,
BSONObj info = 0 
)
inline

Perform a repair and compaction of the specified database.

May take a long time to run. Disk space must be available equal to the size of the database while repairing.

bool mongo::DBClientWithCommands::resetError ( )
inline

Reset the previous error state for this connection (accessed via getLastError and getPrevError).

Useful when performing several operations at once and then checking for an error after attempting all operations.

bool mongo::DBClientWithCommands::runCommand ( const string &  dbname,
const BSONObj cmd,
BSONObj info,
int  options = 0 
)
virtual

Run a database command.

Database commands are represented as BSON objects. Common database commands have prebuilt helper functions – see below. If a helper is not available you can directly call runCommand.

Parameters
dbnamedatabase name. Use "admin" for global administrative commands.
cmdthe command object to execute. For example, { ismaster : 1 }
infothe result object the database returns. Typically has { ok : ..., errmsg : ... } fields set.
optionssee enum QueryOptions - normally not needed to run a command
authif set, the BSONObj representation will be appended to the command object sent
Returns
true if the command returned "ok".

Reimplemented in mongo::DBClientConnection.

bool mongo::DBClientWithCommands::simpleCommand ( const string &  dbname,
BSONObj info,
const string &  command 
)

helper function.

run a simple command where the command expression is simply { command : 1 }

Parameters
info– where to put result object. may be null if caller doesn't need that info
command– command name
Returns
true if the command returned "ok".
bool mongo::DBClientWithCommands::validate ( const string &  ns,
bool  scandata = true 
)
inline

validate a collection, checking for errors and reporting back statistics.

this operation is slow and blocking.

Member Data Documentation

logger::LogSeverity mongo::DBClientWithCommands::_logLevel

controls how chatty the client is about network errors & such.

See log.h


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