MongoDB C++ Driver legacy-1.1.2
Loading...
Searching...
No Matches
Classes | Public Types | Public Member Functions | Static Public Member Functions | 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:

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
 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 Member Functions

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
 

Static Public Member Functions

static std::string MONGO_CLIENT_FUNC getLastErrorString (const BSONObj &res)
 Can be called with the returned value from getLastErrorDetailed to extract an error string.
 

Public Attributes

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

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
 
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.
 

Protected Attributes

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

Detailed Description

DB "commands" Basically just invocations of connection.

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

Member Typedef Documentation

◆ RunCommandHookFunc

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

◆ ProfilingLevel

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

◆ _authMongoCR()

bool mongo::DBClientWithCommands::_authMongoCR ( const std::string &  dbname,
const std::string &  username,
const std::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".

◆ _authX509()

bool mongo::DBClientWithCommands::_authX509 ( const std::string &  dbname,
const std::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".

◆ auth() [1/2]

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.

◆ auth() [2/2]

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

Authentication is separate for each database on the server – you may authenticate for any number of databases on a single connection.

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

◆ availableOptions()

QueryOptions mongo::DBClientWithCommands::availableOptions ( )
protected

Look up the options available on this client.

Caches the answer from _lookupAvailableOptions(), below.

◆ copyDatabase()

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

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

◆ createCollection()

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

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.

◆ createCollectionWithOptions()

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

Allows for a user to provide a BSONObj that contains extra options.

Parameters
extraOptionsAdd extra parameters to the create collection command for features that are version specific or for which default values have flipped between server releases. Some examples are "usePowerOf2Sizes" and "autoIndexId".
Warning
Options set in extraOptions which shadow those passed in as parameters will have indeterminate behavior.
See also
the form of createCollection with less parameters above.
http://docs.mongodb.org/manual/reference/command/create/#dbcmd.create for available options.

◆ createIndex() [1/2]

void mongo::DBClientWithCommands::createIndex ( const StringData ns,
const BSONObj keys 
)
inline

Create an index on the collection 'ns' as described by the given keys.

If you wish to specify options, see the more flexible overload of 'createIndex' which takes an IndexSpec object. Failure to construct the index is reported by throwing an OperationException.

Parameters
nsNamespace on which to create the index
keysDocument describing keys and index types. You must provide at least one field and its direction.

◆ createIndex() [2/2]

virtual void mongo::DBClientWithCommands::createIndex ( const StringData ns,
const IndexSpec descriptor 
)
virtual

Create an index on the collection 'ns' as described by the given descriptor.

Failure to construct the index is reported by throwing an OperationException.

Parameters
nsNamespace on which to create the index
descriptorConfiguration object describing the index to create. The descriptor must describe at least one key and index type.

◆ distinct()

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

Parameters
nsThe namespace to query for distinct values.
fieldThe field for which to return distinct values. Examples: "name", "address.street"
queryOptional query that specifies a filter for documents from which to retrieve distinct values.

◆ dropCollection()

virtual bool mongo::DBClientWithCommands::dropCollection ( const std::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.

◆ enumerateCollections()

std::auto_ptr< DBClientCursor > mongo::DBClientWithCommands::enumerateCollections ( const std::string &  db,
const BSONObj filter = BSONObj(),
int  batchSize = 0 
)

Returns a DBClientCursor with collection information objects.

Example collection information object: { "name" : "mongo_cxx_driver", "options" : { "flags" : 1 } }

◆ eval()

bool mongo::DBClientWithCommands::eval ( const std::string &  dbname,
const std::string &  jscode,
BSONObj info,
BSONElement retValue,
BSONObj args = 0,
bool  nolock = false 
)
inline

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 "log() << 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. nolock if true, the server will not take a global write lock when executing the jscode.

returns true if runs ok.

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

◆ getDatabaseNames()

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

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

throws on error

◆ getIndexNames()

virtual std::list< std::string > mongo::DBClientWithCommands::getIndexNames ( const std::string &  ns,
int  options = 0 
)
virtual

Enumerates all indexes on ns (a db-qualified collection name).

Returns a list of the index names.

◆ getLastError()

std::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.

◆ getLastErrorDetailed()

virtual 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.

◆ getLastErrorString()

static std::string MONGO_CLIENT_FUNC 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.

◆ getPrevError()

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.

◆ group()

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

Note
WARNING: Use of the group command is strongly discouraged, it is much better to use the aggregation framework to acheive similar functionality.
See also
http://docs.mongodb.org/manual/reference/method/db.collection.group
Parameters
nsThe namespace to group
keyThe field or fields to group specified as a projection document: { field: 1 }
jsreduceAn aggregation function that operates on the documents during the group ing operation. The function should take two arguments: the current document and an aggregation result for that group.
outputThe output vector.
initialInitial aggregation result document.
queryOptional selection criteria to determine which documents to process.
finalizeOptional function that runs for each item in the result set before returning the final values in the output vector.

◆ groupWithKeyFunction()

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

This allows for grouping on calculated fields rather on existing fields alone.

See also
DBClientWithCommands::group

◆ isMaster()

virtual 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.

◆ logout()

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

◆ mapreduce()

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

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.

◆ repairDatabase()

bool mongo::DBClientWithCommands::repairDatabase ( const std::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.

◆ resetError()

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.

◆ runCommand()

virtual bool mongo::DBClientWithCommands::runCommand ( const std::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.

◆ simpleCommand()

bool mongo::DBClientWithCommands::simpleCommand ( const std::string &  dbname,
BSONObj info,
const std::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".

◆ validate()

bool mongo::DBClientWithCommands::validate ( const std::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

◆ _logLevel

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 file: