MongoDB C++ Driver
legacy-1.1.2
|
DB "commands" Basically just invocations of connection. More...
#include <dbclientinterface.h>
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. More... | |
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. More... | |
virtual bool | runCommand (const std::string &dbname, const BSONObj &cmd, BSONObj &info, int options=0) |
Run a database command. More... | |
void | auth (const BSONObj ¶ms) |
Authenticate a user. More... | |
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. More... | |
virtual void | logout (const std::string &dbname, BSONObj &info) |
Logs out the connection for the given database. More... | |
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. More... | |
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. More... | |
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. More... | |
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. More... | |
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. 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 std::string &ns, BSONObj *info=NULL) |
Delete the specified collection. More... | |
bool | repairDatabase (const std::string &dbname, BSONObj *info=0) |
Perform a repair and compaction of the specified database. More... | |
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. More... | |
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. More... | |
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. More... | |
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. More... | |
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. More... | |
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. More... | |
bool | validate (const std::string &ns, bool scandata=true) |
validate a collection, checking for errors and reporting back statistics. More... | |
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. More... | |
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< BSONObj > | getCollectionInfos (const std::string &db, const BSONObj &filter=BSONObj()) |
{ name : "<short collection name>", options : { } } | |
std::auto_ptr< DBClientCursor > | enumerateCollections (const std::string &db, const BSONObj &filter=BSONObj(), int batchSize=0) |
Returns a DBClientCursor with collection information objects. More... | |
void | createIndex (const StringData &ns, const BSONObj &keys) |
Create an index on the collection 'ns' as described by the given keys. More... | |
virtual void | createIndex (const StringData &ns, const IndexSpec &descriptor) |
Create an index on the collection 'ns' as described by the given descriptor. More... | |
virtual std::list< std::string > | getIndexNames (const std::string &ns, int options=0) |
Enumerates all indexes on ns (a db-qualified collection name). More... | |
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. More... | |
void | save (const StringData &ns, const BSONObj &toSave, const WriteConcern *wc=NULL) |
Saves a document to a collection. More... | |
virtual std::auto_ptr< DBClientCursor > | getMore (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. More... | |
Public Attributes | |
logger::LogSeverity | _logLevel |
controls how chatty the client is about network errors & such. More... | |
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. More... | |
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. More... | |
bool | _authX509 (const std::string &dbname, const std::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. | |
DB "commands" Basically just invocations of connection.
$cmd.findOne({...});
typedef stdx::function<void(BSONObjBuilder*)> mongo::DBClientWithCommands::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.
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.
|
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".
|
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 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.
digestPassword | if password is plain text, set this to true. otherwise assumed to be pre-digested | |
[out] | authLevel | level of authentication for the given user |
|
protected |
Look up the options available on this client.
Caches the answer from _lookupAvailableOptions(), below.
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
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.
ns | fully qualified collection name |
size | desired 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. |
capped | if true, this is a fixed size collection (where old data rolls out). |
max | maximum number of objects if capped (optional). |
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.
extraOptions | Add 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". |
|
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.
ns | Namespace on which to create the index |
keys | Document describing keys and index types. You must provide at least one field and its direction. |
|
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.
ns | Namespace on which to create the index |
descriptor | Configuration object describing the index to create. The descriptor must describe at least one key and index type. |
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.
ns | The namespace to query for distinct values. |
field | The field for which to return distinct values. Examples: "name", "address.street" |
query | Optional query that specifies a filter for documents from which to retrieve distinct values. |
|
inlinevirtual |
Delete the specified collection.
info | An 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. |
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 } }
|
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.
std::list<std::string> mongo::DBClientWithCommands::getDatabaseNames | ( | ) |
get a list of all the current databases uses the { listDatabases : 1 } command.
throws on error
|
virtual |
Enumerates all indexes on ns (a db-qualified collection name).
Returns a list of the index names.
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.
|
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.
If "w" is -1, wait for propagation to majority of nodes. If "wtimeout" is 0, the operation will block indefinitely if needed.
|
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.
result.err will be null if no error has occurred.
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.
ns | The namespace to group |
key | The field or fields to group specified as a projection document: { field: 1 } |
jsreduce | An 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. |
output | The output vector. |
initial | Initial aggregation result document. |
query | Optional selection criteria to determine which documents to process. |
finalize | Optional function that runs for each item in the result set before returning the final values in the output vector. |
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.
|
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.
|
virtual |
Logs out the connection for the given database.
dbname | the database to logout from. |
info | the 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 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.
|
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.
|
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.
|
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.
dbname | database name. Use "admin" for global administrative commands. |
cmd | the command object to execute. For example, { ismaster : 1 } |
info | the result object the database returns. Typically has { ok : ..., errmsg : ... } fields set. |
options | see enum QueryOptions - normally not needed to run a command |
auth | if set, the BSONObj representation will be appended to the command object sent |
Reimplemented in mongo::DBClientConnection.
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 }
info | – where to put result object. may be null if caller doesn't need that info |
command | – command name |
|
inline |
validate a collection, checking for errors and reporting back statistics.
this operation is slow and blocking.
logger::LogSeverity mongo::DBClientWithCommands::_logLevel |
controls how chatty the client is about network errors & such.
See log.h