23#include <boost/thread/locks.hpp>
24#include <boost/thread/mutex.hpp>
26#include "mongo/config.h"
28#include "mongo/base/string_data.h"
29#include "mongo/client/bulk_operation_builder.h"
30#include "mongo/client/exceptions.h"
31#include "mongo/client/export_macros.h"
32#include "mongo/client/index_spec.h"
33#include "mongo/client/write_concern.h"
34#include "mongo/client/write_options.h"
36#include "mongo/logger/log_severity.h"
37#include "mongo/platform/atomic_word.h"
38#include "mongo/stdx/functional.h"
39#include "mongo/util/mongoutils/str.h"
40#include "mongo/util/net/message.h"
41#include "mongo/util/net/message_port.h"
46enum MONGO_CLIENT_API QueryOptions {
69 QueryOption_OplogReplay = 1 << 3,
107enum MONGO_CLIENT_API WriteOptions {
109 WriteOption_FromWriteback = 1 << 31
118enum MONGO_CLIENT_API ReservedOptions {
119 Reserved_InsertOption_ContinueOnError = 1 << 0,
120 Reserved_FromWriteback = 1 << 1
123enum MONGO_CLIENT_API ReadPreference {
155class MONGO_CLIENT_API DBClientBase;
156class MONGO_CLIENT_API DBClientConnection;
188 enum ConnectionType { INVALID, MASTER, PAIR, SET, CUSTOM };
198 _servers.push_back(server);
202 ConnectionString(ConnectionType type,
const std::string& s,
const std::string& setName =
"") {
209 verify(_servers.size() == 1);
212 verify(_setName.size());
213 verify(_servers.size() >= 1);
216 verify(_servers.size() == 2);
219 verify(_servers.size() > 0);
225 ConnectionString(
const std::string& s, ConnectionType favoredMultipleType) {
229 if (_type != INVALID) {
231 }
else if (_servers.size() == 1) {
234 _type = favoredMultipleType;
235 verify(_type == SET);
240 bool isValid()
const {
241 return _type != INVALID;
244 std::string toString()
const {
248 DBClientBase* connect(std::string& errmsg,
double socketTimeout = 0)
const;
250 std::string getSetName()
const {
254 const std::vector<HostAndPort>& getServers()
const {
258 ConnectionType type()
const {
262 const std::string& getUser()
const {
266 const std::string& getPassword()
const {
270 const BSONObj& getOptions()
const {
274 const std::string& getDatabase()
const {
287 parse(
const std::string& address, std::string& errmsg);
290 parseDeprecated(
const std::string& address, std::string& errmsg);
292 static std::string MONGO_CLIENT_FUNC typeToString(ConnectionType type);
307 double socketTimeout) = 0;
311 boost::lock_guard<boost::mutex> lk(_connectHookMutex);
315 static ConnectionHook* getConnectionHook() {
316 boost::lock_guard<boost::mutex> lk(_connectHookMutex);
321 bool operator<(
const ConnectionString& other)
const {
322 return _string < other._string;
330 static ConnectionString mock(
const HostAndPort& server) {
331 ConnectionString connStr;
332 connStr._servers.push_back(server);
333 connStr._string = server.toString();
338 ConnectionString(ConnectionType type,
339 const std::string& user,
340 const std::string& password,
341 const std::string& servers,
342 const std::string& database,
343 const std::string& setName,
344 const BSONObj& options)
352 _fillServers(servers,
false);
355 verify(_servers.size() == 1);
358 verify(_setName.size());
359 verify(_servers.size() >= 1);
362 verify(_servers.size() == 2);
365 verify(_servers.size() > 0);
371 static ConnectionString _parseURL(
const std::string& url, std::string& errmsg);
373 void _fillServers(std::string s,
bool legacy =
true);
376 BSONObj _makeAuthObjFromOptions(
int maxWireVersion)
const;
378 ConnectionType _type;
379 std::vector<HostAndPort> _servers;
381 std::string _setName;
384 std::string _password;
386 std::string _database;
389 static boost::mutex _connectHookMutex;
390 static ConnectionHook* _connectHook;
395class DBClientCursorBatchIterator;
412 Query(
const std::string& json);
413 Query(
const char* json);
432 sort(BSON(field << asc));
442 Query& hint(
const std::string& indexName);
493 Query& where(
const std::string& jscode) {
494 return where(jscode,
BSONObj());
510 static bool MONGO_CLIENT_FUNC isComplex(
const BSONObj& obj,
bool* hasDollar = 0);
516 int getMaxTimeMs()
const;
517 bool isExplain()
const;
523 bool hasReadPreference()
const;
524 bool hasHint()
const;
525 bool hasMaxTimeMs()
const;
527 std::string toString()
const;
528 operator std::string()
const {
535 void appendComplex(
const char* fieldName,
const T& val) {
566 _ntoreturn(ntoreturn),
574 bool isEmpty()
const {
575 return _ns.size() == 0;
578 bool isExplain()
const {
579 return _queryObj.isExplain();
582 return _queryObj.getFilter();
586 return _queryObj.getHint();
589 return _queryObj.getSort();
602 const BSONObj* fieldsPtr()
const {
606 std::string ns()
const {
609 int ntoskip()
const {
612 int ntoreturn()
const {
615 int options()
const {
623 std::string toString()
const {
624 return str::stream() <<
"QSpec " << BSON(
"ns" << _ns <<
"n2skip" << _ntoskip <<
"n2return"
625 << _ntoreturn <<
"options" << _options
626 <<
"query" << _query <<
"fields" << _fields);
634#define MONGO_QUERY(x) ::mongo::Query(BSON(x))
638MONGO_CLIENT_API std::string MONGO_CLIENT_FUNC
nsGetDB(
const std::string& ns);
653 bool assertOk =
true,
654 std::string* actualServer = 0) = 0;
655 virtual void say(
Message& toSend,
bool isRetry =
false, std::string* actualServer = 0) = 0;
656 virtual void sayPiggyBack(
Message& toSend) = 0;
658 virtual bool recv(
Message& m) {
663 virtual void checkResponse(
const char* data,
666 std::string* targetHost = NULL) {
672 virtual bool lazySupported()
const = 0;
680 virtual std::auto_ptr<DBClientCursor> query(
const std::string& ns,
684 const BSONObj* fieldsToReturn = 0,
685 int queryOptions = 0,
686 int batchSize = 0) = 0;
688 virtual void insert(
const std::string& ns,
693 virtual void insert(
const std::string& ns,
694 const std::vector<BSONObj>& v,
698 virtual void remove(
const std::string& ns,
700 bool justOne =
false,
703 virtual void remove(
const std::string& ns,
708 virtual void update(
const std::string& ns,
715 virtual void update(
const std::string& ns,
729 const BSONObj* fieldsToReturn = 0,
730 int queryOptions = 0);
736 void findN(std::vector<BSONObj>& out,
737 const std::string& ns,
741 const BSONObj* fieldsToReturn = 0,
742 int queryOptions = 0,
758 virtual std::string getServerAddress()
const = 0;
761 virtual std::auto_ptr<DBClientCursor>
getMore(
const std::string& ns,
764 int options = 0) = 0;
777 : _logLevel(logger::LogSeverity::Log()),
780 _cachedAvailableOptions((enum QueryOptions)0),
781 _haveCachedAvailableOptions(false) {}
843 bool auth(
const std::string& dbname,
844 const std::string& username,
845 const std::string& pwd,
847 bool digestPassword =
true);
861 virtual unsigned long long count(
const std::string& ns,
867 static std::string MONGO_CLIENT_FUNC
930 const std::string& db,
bool fsync =
false,
bool j =
false,
int w = 0,
int wtimeout = 0);
934 std::string
getLastError(
bool fsync =
false,
bool j =
false,
int w = 0,
int wtimeout = 0);
944 const std::string& db,
bool fsync =
false,
bool j =
false,
int w = 0,
int wtimeout = 0);
971 return simpleCommand(
"admin", 0,
"reseterror");
981 uassert(10011,
"no collection name", coll.size());
988 bool res = runCommand(db.c_str(), BSON(
"drop" << coll), *info);
996 return simpleCommand(dbname, info,
"repairDatabase");
1020 const std::string& todb,
1021 const std::string& fromhost =
"",
1022 const std::string& mechanism =
"DEFAULT",
1023 const std::string& username =
"",
1024 const std::string& password =
"",
1037 bool setDbProfilingLevel(
const std::string& dbname, ProfilingLevel level,
BSONObj* info = 0);
1038 bool getDbProfilingLevel(
const std::string& dbname, ProfilingLevel& level,
BSONObj* info = 0);
1045 MROutput(
const char* collection) : out(BSON(
"replace" << collection)) {}
1046 MROutput(
const std::string& collection) : out(BSON(
"replace" << collection)) {}
1077 const std::string& jsmapf,
1078 const std::string& jsreducef,
1104 std::vector<BSONObj>* output,
1119 std::vector<BSONObj>* output,
1153 MONGO_CLIENT_DEPRECATED(
"deprecated in MongoDB 3.0")
1154 bool eval(const std::
string& dbname,
1155 const std::
string& jscode,
1159 bool nolock = false) {
1160 return evalDeprecated(dbname, jscode, info, retValue, args, nolock);
1163 bool evalDeprecated(
const std::string& dbname,
1164 const std::string& jscode,
1168 bool nolock =
false);
1173 bool validate(
const std::string& ns,
bool scandata =
true) {
1176 return runCommand(
nsGetDB(ns).c_str(), cmd, info);
1183 MONGO_CLIENT_DEPRECATED(
"deprecated in MongoDB 3.0")
1184 bool eval(const std::
string& dbname, const std::
string& jscode) {
1185 return evalDeprecated(dbname, jscode);
1188 bool evalDeprecated(
const std::string& dbname,
const std::string& jscode);
1191 MONGO_CLIENT_DEPRECATED(
"deprecated in MongoDB 3.0") bool eval(const std::
string& dbname,
1192 const std::
string& jscode,
1194 return evalDeprecated(dbname, jscode, parm1);
1198 bool evalDeprecated(
const std::string& dbname,
const std::string& jscode, T parm1) {
1200 BSONElement retValue;
1203 BSONObj args = b.
done();
1204 return eval(dbname, jscode, info, retValue, &args);
1210 template <
class T,
class NumType>
1212 const std::
string& jscode,
1215 return evalDeprecated(dbname, jscode, parm1, ret);
1218 template <
class T,
class NumType>
1219 bool evalDeprecated(
const std::string& dbname,
1220 const std::string& jscode,
1228 if (!eval(dbname, jscode, info, retValue, &args))
1230 ret = (NumType)retValue.
number();
1268 bool exists(
const std::string& ns);
1280 return createIndex(ns,
IndexSpec().addKeys(keys));
1293 virtual std::list<BSONObj> getIndexSpecs(
const std::string& ns,
int options = 0);
1299 virtual std::list<std::string>
getIndexNames(
const std::string& ns,
int options = 0);
1301 virtual std::auto_ptr<DBClientCursor> enumerateIndexes(
const std::string& ns,
1305 virtual void dropIndex(
const std::string& ns,
BSONObj keys);
1306 virtual void dropIndex(
const std::string& ns,
const std::string& indexName);
1313 virtual void reIndex(
const std::string& ns);
1315 static std::string genIndexName(
const BSONObj& keys);
1319 bool ret = simpleCommand(dbname, info,
"dropDatabase");
1323 virtual std::string toString()
const = 0;
1335 return _runCommandHook;
1345 return _postRunCommandHook;
1356 BSONObj _countCmd(
const std::string& ns,
const Query& query,
int options,
int limit,
int skip);
1364 virtual QueryOptions _lookupAvailableOptions();
1366 virtual void _auth(
const BSONObj& params);
1374 const std::string& username,
1375 const std::string& pwd,
1377 bool digestPassword);
1391 int _minWireVersion;
1392 int _maxWireVersion;
1396 enum QueryOptions _cachedAvailableOptions;
1397 bool _haveCachedAvailableOptions;
1409 std::vector<BSONObj>* output);
1411 std::auto_ptr<DBClientCursor> _legacyCollectionInfo(
const std::string& db,
1426 static AtomicInt64 ConnectionIdSequence;
1427 long long _connectionId;
1428 const boost::scoped_ptr<DBClientWriter> _wireProtocolWriter;
1429 const boost::scoped_ptr<DBClientWriter> _commandWriter;
1431 int _maxBsonObjectSize;
1432 int _maxMessageSizeBytes;
1433 int _maxWriteBatchSize;
1434 void _write(
const std::string& ns,
1435 const std::vector<WriteOperation*>& writes,
1437 bool bypassDocumentValidation,
1442 static const uint64_t INVALID_SOCK_CREATION_TIME;
1450 long long getConnectionId()
const {
1451 return _connectionId;
1455 return _writeConcern;
1461 void setWireVersions(
int minWireVersion,
int maxWireVersion) {
1462 _minWireVersion = minWireVersion;
1463 _maxWireVersion = maxWireVersion;
1466 virtual int getMinWireVersion() {
1467 return _minWireVersion;
1469 virtual int getMaxWireVersion() {
1470 return _maxWireVersion;
1472 int getMaxBsonObjectSize() {
1473 return _maxBsonObjectSize;
1475 int getMaxMessageSizeBytes() {
1476 return _maxMessageSizeBytes;
1478 int getMaxWriteBatchSize() {
1479 return _maxWriteBatchSize;
1497 virtual std::auto_ptr<DBClientCursor>
query(
const std::string& ns,
1501 const BSONObj* fieldsToReturn = 0,
1502 int queryOptions = 0,
1526 std::vector<DBClientCursor*>* cursors,
1529 virtual std::auto_ptr<DBClientCursor> aggregate(
const std::string& ns,
1531 const BSONObj* aggregateOptions = NULL,
1532 int queryOptions = 0);
1544 const std::string& ns,
1546 const BSONObj* fieldsToReturn = 0,
1547 int queryOptions = 0);
1550 const std::string& ns,
1552 const BSONObj* fieldsToReturn = 0,
1553 int queryOptions = 0);
1561 virtual std::auto_ptr<DBClientCursor>
getMore(
const std::string& ns,
1578 const std::vector<BSONObj>& v,
1588 bool upsert =
false,
1592 virtual void update(
1612 bool upsert =
false,
1613 bool returnNew =
false,
1617 bool bypassDocumentValidation =
false);
1663 virtual void remove(
const std::string& ns,
1668 virtual bool isFailed()
const = 0;
1675 virtual void killCursor(
long long cursorID) = 0;
1681 virtual ConnectionString::ConnectionType type()
const = 0;
1683 virtual double getSoTimeout()
const = 0;
1685 virtual uint64_t getSockCreationMicroSec()
const {
1686 return INVALID_SOCK_CREATION_TIME;
1689 virtual void reset() {}
1692 void _findAndModify(
const StringData& ns,
1693 const BSONObj& query,
1694 const BSONObj& update,
1695 const BSONObj& sort,
1698 const BSONObj& fields,
1699 const WriteConcern* wc,
1700 bool bypassDocumentValidation,
1701 BSONObjBuilder* out);
1705class DBClientReplicaSet;
1718 using DBClientBase::query;
1728 double so_timeout = 0);
1731 _numConnections.fetchAndAdd(-1);
1746 bool connect(
const std::string& server, std::string& errmsg) {
1761 if (!connect(
HostAndPort(serverHostname), errmsg))
1774 virtual std::auto_ptr<DBClientCursor>
query(
const std::string& ns,
1778 const BSONObj* fieldsToReturn = 0,
1779 int queryOptions = 0,
1783 const std::string& ns,
1785 const BSONObj* fieldsToReturn,
1802 return p ? p->isStillConnected() :
true;
1810 std::string toString()
const {
1811 std::stringstream ss;
1812 ss << _serverString;
1813 if (!_serverAddrString.empty())
1814 ss <<
" (" << _serverAddrString <<
")";
1820 std::string getServerAddress()
const {
1821 return _serverString;
1823 const HostAndPort& getServerHostAndPort()
const {
1827 virtual void killCursor(
long long cursorID);
1828 virtual bool callRead(Message& toSend, Message& response) {
1829 return call(toSend, response);
1831 virtual void say(Message& toSend,
bool isRetry =
false, std::string* actualServer = 0);
1832 virtual bool recv(Message& m);
1833 virtual void checkResponse(
const char* data,
1836 std::string* host = NULL);
1839 bool assertOk =
true,
1840 std::string* actualServer = 0);
1841 virtual ConnectionString::ConnectionType type()
const {
1842 return ConnectionString::MASTER;
1844 void setSoTimeout(
double timeout);
1845 double getSoTimeout()
const {
1849 virtual bool lazySupported()
const {
1853 static int MONGO_CLIENT_FUNC getNumConnections() {
1854 return _numConnections.load();
1863 static void MONGO_CLIENT_FUNC setLazyKillCursor(
bool lazy) {
1864 _lazyKillCursor = lazy;
1866 static bool MONGO_CLIENT_FUNC getLazyKillCursor() {
1867 return _lazyKillCursor;
1870 uint64_t getSockCreationMicroSec()
const;
1873 virtual void _auth(
const BSONObj& params);
1874 virtual void sayPiggyBack(Message& toSend);
1876 boost::scoped_ptr<MessagingPort> p;
1877 boost::scoped_ptr<SockAddr> server;
1879 const bool autoReconnect;
1880 Backoff autoReconnectBackoff;
1881 HostAndPort _server;
1882 std::string _serverString;
1883 std::string _serverAddrString;
1884 void _checkConnection();
1887 void checkConnection() {
1892 std::map<std::string, BSONObj> authCache;
1894 bool _connect(std::string& errmsg);
1896 static AtomicInt32 _numConnections;
1897 static bool _lazyKillCursor;
1900 SSLManagerInterface* sslManager();
1909 void handleNotMasterResponse(
const BSONElement& elemToCheck);
1913 std::string _parentReplSetName;
1918MONGO_CLIENT_API
bool MONGO_CLIENT_FUNC
serverAlive(
const std::string& uri);
1921MONGO_CLIENT_API
bool MONGO_CLIENT_FUNC hasErrField(
const BSONObj& result);
1923MONGO_CLIENT_API
inline std::ostream& MONGO_CLIENT_FUNC
1924operator<<(std::ostream& s,
const Query& q) {
1925 return s << q.toString();
BSONElement represents an "element" in a BSONObj.
Definition bsonelement.h:55
double number() const
Retrieve the numeric value of the element.
Definition bsonelement.h:290
Definition bson_field.h:76
Utility for creating a BSONObj.
Definition bsonobjbuilder.h:53
BSONObjBuilder & append(const BSONElement &e)
append element to the object we are building
Definition bsonobjbuilder.h:124
BSONObjBuilder & appendElements(BSONObj x)
add all the fields from the object specified to this object
BSONObj obj()
destructive The returned BSONObj will free the buffer when it is finished.
Definition bsonobjbuilder.h:618
BSONObj done()
Fetch the object we have built.
Definition bsonobjbuilder.h:631
C++ representation of a "BSON" object – that is, an extended JSON-style object in a binary representa...
Definition bsonobj.h:78
BSONObj getOwned() const
assure the data buffer is under the control of this BSONObj and not a remote buffer
Class for constructing and executing bulk operations against MongoDB via a fluent API.
Definition bulk_operation_builder.h:54
Definition dbclientinterface.h:1707
Definition dbclientinterface.h:300
ConnectionString can parse MongoDB URIs with the following format:
Definition dbclientinterface.h:186
bool sameLogicalEndpoint(const ConnectionString &other) const
This returns true if this and other point to the same logical entity.
abstract class that implements the core db operations
Definition dbclientinterface.h:1422
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< DBClientCursor > query(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 insert(const std::string &ns, BSONObj obj, int flags=0, const WriteConcern *wc=NULL)
insert an object into the database
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.
virtual BulkOperationBuilder initializeUnorderedBulkOp(const std::string &ns)
Initializes an unordered bulk operation by returning an object that can be used to enqueue multiple o...
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 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 std::auto_ptr< DBClientCursor > getMore(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, const std::vector< BSONObj > &v, int flags=0, const WriteConcern *wc=NULL)
insert a vector of objects into the database
virtual bool isStillConnected()=0
if not checked recently, checks whether the underlying socket/sockets are still valid
virtual BulkOperationBuilder initializeOrderedBulkOp(const std::string &ns)
Initializes an ordered bulk operation by returning an object that can be used to enqueue multiple ope...
virtual void remove(const std::string &ns, Query q, bool justOne=0, const WriteConcern *wc=NULL)
remove matching objects from 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.
A basic connection to the database.
Definition dbclientinterface.h:1716
virtual bool runCommand(const std::string &dbname, const BSONObj &cmd, BSONObj &info, int options=0)
Run a database command.
virtual bool connect(const HostAndPort &server, std::string &errmsg)
Connect to a Mongo database server.
void setParentReplSetName(const std::string &replSetName)
Set the name of the replica set that this connection is associated to.
bool isStillConnected()
if not checked recently, checks whether the underlying socket/sockets are still valid
Definition dbclientinterface.h:1801
DBClientConnection(bool _autoReconnect=false, DBClientReplicaSet *cp=0, double so_timeout=0)
virtual void logout(const std::string &dbname, BSONObj &info)
Logs out the connection for the given database.
bool connect(const std::string &server, std::string &errmsg)
Compatibility connect now that HostAndPort has an explicit constructor.
Definition dbclientinterface.h:1746
bool isFailed() const
Definition dbclientinterface.h:1797
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 std::auto_ptr< DBClientCursor > query(const std::string &ns, Query query=Query(), int nToReturn=0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)
send a query to the database.
void connect(const std::string &serverHostname)
Connect to a Mongo database server.
Definition dbclientinterface.h:1759
iterate over objects in current batch only - will not cause a network call
Definition dbclientcursor.h:282
The interface that any db connection should implement.
Definition dbclientinterface.h:678
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.
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
virtual BSONObj findOne(const std::string &ns, const Query &query, const BSONObj *fieldsToReturn=0, int queryOptions=0)
void save(const StringData &ns, const BSONObj &toSave, const WriteConcern *wc=NULL)
Saves a document to a collection.
Use this class to connect to a replica set of servers.
Definition dbclient_rs.h:42
DB "commands" Basically just invocations of connection.
Definition dbclientinterface.h:771
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.
bool _authX509(const std::string &dbname, const std::string &username, BSONObj *info)
Use the MONGODB-X509 protocol to authenticate as "username.
std::list< BSONObj > getCollectionInfos(const std::string &db, const BSONObj &filter=BSONObj())
{ name : "<short collection name>", options : { } }
bool validate(const std::string &ns, bool scandata=true)
validate a collection, checking for errors and reporting back statistics.
Definition dbclientinterface.h:1173
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 ...
bool isNotMasterErrorString(const BSONElement &e)
if the element contains a not master error
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...
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",...
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.
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.
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.
QueryOptions availableOptions()
Look up the options available on this client.
RunCommandHookFunc _runCommandHook
These functions will be executed by the driver on runCommand calls.
Definition dbclientinterface.h:1389
bool repairDatabase(const std::string &dbname, BSONObj *info=0)
Perform a repair and compaction of the specified database.
Definition dbclientinterface.h:995
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.
static std::string MONGO_CLIENT_FUNC getLastErrorString(const BSONObj &res)
Can be called with the returned value from getLastErrorDetailed to extract an error string.
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...
virtual bool dropCollection(const std::string &ns, BSONObj *info=NULL)
Delete the specified collection.
Definition dbclientinterface.h:978
virtual void dropIndexes(const std::string &ns)
drops all indexes for the collection
logger::LogSeverity _logLevel
controls how chatty the client is about network errors & such.
Definition dbclientinterface.h:774
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.
virtual bool dropDatabase(const std::string &dbname, BSONObj *info=0)
Erase / drop an entire database.
Definition dbclientinterface.h:1318
void createIndex(const StringData &ns, const BSONObj &keys)
Create an index on the collection 'ns' as described by the given keys.
Definition dbclientinterface.h:1279
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
Definition dbclientinterface.h:1211
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.
ProfilingLevel
The Mongo database provides built-in performance profiling capabilities.
Definition dbclientinterface.h:1031
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 createIndex(const StringData &ns, const IndexSpec &descriptor)
Create an index on the collection 'ns' as described by the given descriptor.
std::list< std::string > getCollectionNames(const std::string &db, const BSONObj &filter=BSONObj())
Get a list of all the current collections in db.
virtual bool runCommand(const std::string &dbname, const BSONObj &cmd, BSONObj &info, int options=0)
Run a database command.
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.
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.
Definition dbclientinterface.h:1342
virtual bool isMaster(bool &isMaster, BSONObj *info=0)
returns true in isMaster parm if this db is the current master of a replica pair.
virtual void logout(const std::string &dbname, BSONObj &info)
Logs out the connection for the given database.
stdx::function< void(BSONObjBuilder *)> RunCommandHookFunc
A function type for runCommand hooking; the function takes a pointer to a BSONObjBuilder and returns ...
Definition dbclientinterface.h:1332
virtual std::list< std::string > getIndexNames(const std::string &ns, int options=0)
Enumerates all indexes on ns (a db-qualified collection name).
std::auto_ptr< DBClientCursor > enumerateCollections(const std::string &db, const BSONObj &filter=BSONObj(), int batchSize=0)
Returns a DBClientCursor with collection information objects.
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).
Definition dbclientinterface.h:970
bool isOk(const BSONObj &)
if the result of a command is ok
void auth(const BSONObj ¶ms)
Authenticate a user.
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 ...
std::list< std::string > getDatabaseNames()
get a list of all the current databases uses the { listDatabases : 1 } command.
bool simpleCommand(const std::string &dbname, BSONObj *info, const std::string &command)
helper function.
Definition dbclient_writer.h:27
interface that handles communication with the db
Definition dbclientinterface.h:646
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)
Definition index_spec.h:29
Definition message_port.h:74
Represents a full query description, including all options required for the query to be passed on to ...
Definition dbclientinterface.h:548
Represents a Mongo query expression.
Definition dbclientinterface.h:403
Query & maxKey(const BSONObj &val)
max is exclusive
Query & sort(const std::string &field, int asc=1)
Add a sort (ORDER BY) criteria to the query expression.
Definition dbclientinterface.h:431
Query & hint(BSONObj keyPattern)
Provide a hint to the query.
Query & sort(const BSONObj &sortPattern)
Add a sort (ORDER BY) criteria to the query expression.
static bool MONGO_CLIENT_FUNC hasReadPreference(const BSONObj &queryObj)
bool isComplex(bool *hasDollar=0) const
Query & maxTimeMs(int millis)
Specifies a cumulative time limit in milliseconds for processing an operation.
Query & explain()
Return explain information about execution of this query instead of the actual query results.
Query & readPref(ReadPreference pref, const BSONArray &tags)
Sets the read preference for this query.
Query & snapshot()
Use snapshot mode for the query.
Query & where(const std::string &jscode, BSONObj scope)
Queries to the Mongo database support a $where parameter option which contains a javascript function ...
Query & minKey(const BSONObj &val)
Provide min and/or max index limits for the query.
A StringData object wraps a 'const string&' or a 'const char*' without copying its contents.
Definition string_data.h:43
Definition assert_util.h:145
Class to encapsulate client side "Write Concern" concept.
Definition write_concern.h:35
Represents a single server side write operation and encapsulates the process for encoding the operati...
Definition write_operation.h:31
Class representing the result of a write operations sent to the server.
Definition write_result.h:33
Representation of the severity / priority of a log message.
Definition log_severity.h:33
the idea here is to make one liners easy.
Definition str.h:44
ReadPreference_Nearest
Read from any member.
Definition dbclientinterface.h:152
ReadPreference_SecondaryOnly
Read from secondary if available, otherwise error.
Definition dbclientinterface.h:142
QueryOption_PartialResults
When sharded, this means its ok to return partial results Usually we will fail a query if all require...
Definition dbclientinterface.h:97
QueryOption_SlaveOk
allow query of replica slave.
Definition dbclientinterface.h:59
QueryOption_Exhaust
Stream the data down full blast in multiple "more" packages, on the assumption that the client will f...
Definition dbclientinterface.h:91
QueryOption_AwaitData
Use with QueryOption_CursorTailable.
Definition dbclientinterface.h:80
QueryOption_NoCursorTimeout
The server normally times out idle cursors after an inactivity period to prevent excess memory uses S...
Definition dbclientinterface.h:75
ReadPreference_PrimaryOnly
Read from primary only.
Definition dbclientinterface.h:129
ReadPreference_SecondaryPreferred
Read from a secondary if available, otherwise read from the primary.
Definition dbclientinterface.h:147
ReadPreference_PrimaryPreferred
Read from primary if available, otherwise a secondary.
Definition dbclientinterface.h:137
QueryOption_CursorTailable
Tailable means cursor is not closed when the last data is retrieved.
Definition dbclientinterface.h:55
Utility functions for parsing numbers from strings.
Definition compare_numbers.h:20
MONGO_CLIENT_API bool MONGO_CLIENT_FUNC serverAlive(const std::string &uri)
pings server to check if it's up
std::string createPasswordDigest(const StringData &username, const StringData &clearTextPassword)
Hashes the password so that it can be stored in a user object or used for MONGODB-CR authentication.
MONGO_CLIENT_API std::string MONGO_CLIENT_FUNC nsGetCollection(const std::string &ns)
MONGO_CLIENT_API std::string MONGO_CLIENT_FUNC nsGetDB(const std::string &ns)
This implicitly converts from char*, string, and BSONObj to be an argument to mapreduce You shouldn't...
Definition dbclientinterface.h:1044
Name of a process on the network.
Definition hostandport.h:37