一、连接类

  DBClientConnection,派生自DBClientBase。DBClientBase类是实现query, update, insert, remove等功能。

  构造函数:DBClientConnection(bool _autoReconnect=false, DBClientReplicaSet* cp=0, double so_timeout=0)

    _autoReconect是否自动重连,默认false

    cp不需要关心,默认值

    so_timeout超时时间,单位是秒

  连接函数:bool connect(const char *hostname, string &errmsg)

    hostname 主机,127.0.0.1,127.0.0.1:5555

    errmsg 错误信息,传出

二、删除文档

  void remove(const string &ns, Query q, bool justOne=0)

    ns 库名.集合名

    q 是一个查询条件。Query是一个类,利用构造函数Query(const char *json);构造。

    justOne 是否删除一条,默认false

三、新增文档

  void insert(const string &ns, BSONObj obj, int flag=0)

    ns 库名.集合名

    BSONObj obj:

      1、通过BSONObjBuilder构造

        

 //通过BSONObjBuilder.obj()生成BSONObj

 //第一种形式
BSONObjBuilder b1;
//{id:1,name:'haha'}
b1.append("id",);
b1.append("name","haha");
/*
BSONObj obj() {
bool own = owned();
massert( 10335 , "builder does not own memory", own );
doneFast();
BSONObj::Holder* h = (BSONObj::Holder*)_b.buf();
decouple(); // sets _b.buf() to NULL
return BSONObj(h);
}
*/
DBClientConnection.insert("dbName.collectionName",b1.obj()); //第二种形式
BSONObjBuilder b2;
//{id:2,name:'hehe'}
/*
template<class T>
BSONObjBuilder& operator<<( T value );
*/
b2<<"id"<<<<"name"<<"hehe";
//余下同上 //第三种形式
/*
#define BSON(x) (( mongo::BSONObjBuilder(64) << x ).obj())
*/
//{id:3,name:'hahe'}
BSONObjBuilder b3=BSON("id"<<<<"name"<<hahe");

      2、通过Query构造

        

 //{id:4,name:'heha'}
Query ins("{id:4,name:'heha'}");
/*
class Query {
public:
BSONObj obj;
Query() : obj(BSONObj()) { }
Query(const BSONObj& b) : obj(b) { }
Query(const string &json);
Query(const char * json);
*/
insert("dbName.collectionName",ins.obj);

四、修改文档

  void update(const string &ns, Query query, BSONObj obj, bool upsert = false, bool multi = false);

  ns 库名.集合名

  query 查询的条件

  obj 更新的内容

  upsert 如果条件不成立是否新增

  multi 是否更新多条

  

 //查询条件
Query query("{id:1}");
//更新内容
Query bobj("{name:'hehe'}");
update("dbName.collectionName",query,bobj.obj);

五、查询文档

  virtual auto_prt<DBClientCursor> query(const string &ns, Query query=Query(), int nToReturn =0, int nToSkip=0, const BSONObj *fieldsToReturn=0, int queryOptions=0, int batchSize=0)

  auto_prt<DBClientCursor> 智能指针,自动释放<>内部的内存数据

    DBClientCursor类,存放查询结果。more()判断调用next是否安全。next()返回BSONObj对象

      DBClientCursor部分源码:

/** Queries return a cursor object */
class DBClientCursor : public DBClientCursorInterface {
public:
/** If true, safe to call next(). Requests more from server if necessary. */
bool more(); /** If true, there is more in our local buffers to be fetched via next(). Returns
false when a getMore request back to server would be required. You can use this
if you want to exhaust whatever data has been fetched to the client already but
then perhaps stop.
*/
int objsLeftInBatch() const { _assertIfNull(); return _putBack.size() + batch.nReturned - batch.pos; }
bool moreInCurrentBatch() { return objsLeftInBatch() > ; } /** next
@return next object in the result cursor.
on an error at the remote server, you will get back:
{ $err: <string> }
if you do not want to handle that yourself, call nextSafe().
*/
BSONObj next();

    ns,query  同前

    nToReturn 返回记录数

    nToSkip 跳过记录数

    fieldsTOReturn 要返回的字段

DBClientConnection conn(false,,);
std::string errmsg;
if (!conn.connect("localhost:27018", errmsg))
{
cout << "connect to mongo err" << endl;
return -;
}
auto_ptr<DBClientCursor> cursor = conn.query("dbName.collectionName", Query("{}"));

    读取查询结果:

      BSONObj重载了<<

        部分源码:

inline std::ostream& operator<<( std::ostream &s, const BSONObj &o ) {
return s << o.toString();
} inline std::string BSONObj::toString( bool isArray, bool full ) const {
if ( isEmpty() ) return "{}";
StringBuilder s;
toString(s, isArray, full);
return s.str();
} inline void BSONObj::toString( StringBuilder& s, bool isArray, bool full, int depth ) const {
if ( isEmpty() ) {
s << "{}";
return;
} s << ( isArray ? "[ " : "{ " );
BSONObjIterator i(*this);
bool first = true;
while ( ) {
massert( , "Object does not end with EOO", i.moreWithEOO() );
BSONElement e = i.next( true );
massert( , "Invalid element size", e.size() > );
massert( , "Element too large", e.size() < ( << ) );
int offset = (int) (e.rawdata() - this->objdata());
massert( , "Element extends past end of object",
e.size() + offset <= this->objsize() );
e.validate();
bool end = ( e.size() + offset == this->objsize() );
if ( e.eoo() ) {
massert( , "EOO Before end of object", end );
break;
}
if ( first )
first = false;
else
s << ", ";
e.toString( s, !isArray, full, depth );
}
s << ( isArray ? " ]" : " }" );
}

      读取指定字段内容

        BSONObj::getField(const StringData& name)

        源码:

inline BSONElement BSONObj::getField(const StringData& name) const {
BSONObjIterator i(*this);
while ( i.more() ) {
BSONElement e = i.next();
if ( strcmp(e.fieldName(), name.data()) == )
return e;
}
return BSONElement();
}

        BSONElement部分源码:

class BSONElement {
public:
/** These functions, which start with a capital letter, throw a UserException if the
element is not of the required type. Example: std::string foo = obj["foo"].String(); // std::exception if not a std::string type or DNE
*/
std::string String() const { return chk(mongo::String).valuestr(); }
Date_t Date() const { return chk(mongo::Date).date(); }
double Number() const { return chk(isNumber()).number(); }
double Double() const { return chk(NumberDouble)._numberDouble(); }
long long Long() const { return chk(NumberLong)._numberLong(); }
int Int() const { return chk(NumberInt)._numberInt(); }
bool Bool() const { return chk(mongo::Bool).boolean(); }
std::vector<BSONElement> Array() const; // see implementation for detailed comments
mongo::OID OID() const { return chk(jstOID).__oid(); }
void Null() const { chk(isNull()); } // throw UserException if not null
void OK() const { chk(ok()); } // throw UserException if element DNE

        读取的字段不存在,程序会出现异常,需要调用hasField(char*)或者hasElement(char*)判断是否有该元素

       示例

while (cursor->more())
{//判断是否有下一条
mongo::BSONObj obj = cursor->next();//取下一条记录,为BSONObj格式
//cout << obj << endl;
//解析数据
cout << "id:" << obj.getField("id").Number() << ",name:" << obj.getField("name").String();
if (obj.hasElement("age"))
{//是否存在该元素
cout << ",age:" << obj.getField("age").Number();
} cout << endl;
}

[笔记]MongoDB 二(Linux下MongoDB API C++编程)的更多相关文章

  1. MongoDB在Linux下常用优化设置

    MongoDB在Linux下常用优化设置 以下是一些MongoDB推荐的常用优化设置.在生产环境下选取合适的参数值,例如预读值和默认文件描述符数目等,会对系统性能有很大的影响. 1.关闭数据库文件的 ...

  2. Linux下mongodb安装及数据导入导出教程

    Linux下mongodb安装及数据导入导出教程 #查看linux发行版本 cat /etc/issue #查看linux内核版本号 uname -r 一.Linux下mongodb安装的一般步骤 1 ...

  3. Linux下MongoDB服务安装

    Linux下MongoDB服务安装 MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.MongoDB是一个介于关系数据库和非关系数据 ...

  4. Linux下mongodb

    Linux下mongodb安装: 新建mongodb文件夹 下载安装包 curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3. ...

  5. MongoDB在linux下的启动

    最近公司数据库用到MongoDB,而之前只关注知道它是分布式非关系数据库,数据以文档的形式存储,数据格式是类似json的bson格式.而对于具体用法以及java如何调用并没有过多接触,今天花费一天的时 ...

  6. Java web与web gis学习笔记(二)——百度地图API调用

    系列链接: Java web与web gis学习笔记(一)--Tomcat环境搭建 Java web与web gis学习笔记(二)--百度地图API调用 JavaWeb和WebGIS学习笔记(三)-- ...

  7. Linux下的C Socket编程 -- 获取对方IP地址

    Linux下的C Socket编程(二) 获取域名对应的IP地址 经过上面的讨论,如果我们想要连接到远程的服务器,我们需要知道对方的IP地址,系统函数gethostbyname便能够实现这个目的.它能 ...

  8. Linux下的C Socket编程 -- 简介与client端的处理

    Linux下的C Socket编程(一) 介绍 Socket是进程间通信的方式之一,是进程间的通信.这里说的进程并不一定是在同一台机器上也有可能是通过网络连接的不同机器上.只要他们之间建立起了sock ...

  9. linux下C语言多线程编程实例

    用一个实例.来学习linux下C语言多线程编程实例. 代码目的:通过创建两个线程来实现对一个数的递加.代码: //包含的头文件 #include <pthread.h> #include ...

随机推荐

  1. CF 1133C Balanced Team

    题目链接:http://codeforces.com/problemset/problem/1133/C 题目分析 (个人感受:我看错了题目,硬是写了近一个小时!) 这个题目要求一个最长的序列,使得这 ...

  2. 在CentOS 7系统下升级 Jenkins版本

    使用yum方式安装的war文件路径:/usr/lib/jenkins/jenkins.war 查看war包所在的目录 find / -name jenkins.war 停止Jenkins 服务 sys ...

  3. [Next] 五.next自定义内容

    自定义 head 这是默认的 head 这样的 head 并不能满足我们的需求.next 公开了一个内置组件,用于将元素追加到<head>标签的.我们可以通过这个自定义 head 新建 c ...

  4. Python爬虫 Selenium与PhantomJS

    Selenium Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动化操作,不同是Sele ...

  5. k-means 非监督学习聚类算法

    非监督学习 非监督学习没有历史样本数据和标签,直接对数据分析或得结果. k-means 使用 >>> from sklearn.cluster import KMeans >& ...

  6. 网络初级篇之OSPF(一)原理

    一.OSPF是什么 Open Shortest Path First, 开放最短路径优先协议,是一种开源的使用最短路径优先(SPF)算法的内部网关协议(IGP).常用于路由器的动态选路. 二.OSPF ...

  7. 解压速度更快, Zstandard 1.4.1 发布

    zstd 1.4.1 发布了,zstd 又叫 Zstandard,它是一种快速无损压缩算法,主要应用于 zlib 级别的实时压缩场景,并且具有更好的压缩比.zstd 还可以以压缩速度为代价提供更强的压 ...

  8. c++的并发操作(多线程)

    C++11标准在标准库中为多线程提供了组件,这意味着使用C++编写与平台无关的多线程程序成为可能,而C++程序的可移植性也得到了有力的保证.另外,并发编程可提高应用的性能,这对对性能锱铢必较的C++程 ...

  9. PAT Basic 1013 数素数 (20 分)

    令 P​i​​ 表示第 i 个素数.现任给两个正整数 M≤N≤10​4​​,请输出 P​M​​ 到 P​N​​ 的所有素数. 输入格式: 输入在一行中给出 M 和 N,其间以空格分隔. 输出格式: 输 ...

  10. SQLServer中跨服务器跨数据库之间的数据操作

    首先必须理解一个概念: select * from sys.servers         (查看系统表,看原来的服务器名) 要想跨域就必须在以上信息中可以检索到! 怎样添加? --创建链接服务器  ...