说明:
IN
表示输入参数;
OUT
表示输出参数;
1.
构造函数
DBClientConnection(bool auto_connect, 0, double so_timeout);
auto_connect(IN)
:连接失败后自动重连
so_timeout(IN)
:非连接超时,tcp的读写超时
2.
连接函数
bool connect(string server, &string errmsg);
返回值:成功/失败
server(IN)
:连接的服务器
errmsg(OUT)
:出错信息
示例:
bool auto_connect = true;
double so_timeout = 3;
string host = "127.0.0.1";
string port = "27017";
string errmsg = "";
DBClientConnection pConn = new DBClientConnection(auto_connect, 0, so_timeout);
pConn->connect(host+":"+port, errmsg);
3.
查询
auto_ptr query(const string &ns, Query query, int nToReturn, int nToSkip,
const BSONObj *fieldsToReturn, int queryOptions , int batchSize);
返回值:结果集
ns(IN)
:命名空间,db_name.collection_name
query(IN)
:查询的条件,相当于mysql中的where
nToReturn
:返回结果条数,相当于limit
nToSkip
:跳过的结果条数,相当于skip
fieldsToReturn
:返回列集合
queryOptions
:详见QueryOptions这个枚举,填0即可
batchSize
:未说明
示例:
string db = "shool";
string collection = "student";
Query condition = QUERY("age"<<20);
int limit = 10;
int offset = 5;
BSONObj columns = BSON("uid"<<1<<"name"<<1);
auto_ptr cursor;
cursor = pConn->query(db+"."+collection, condition, limit, offset, columns, 0, 0);
其效果相当于:
select uid,name from shool.student where age=20 limit 5,10;
对结果集的操作:
int uid=0;
string name="";
while(cursor->more())
{
BSONObj p = cursor->next();
uid = p["uid"].Int();
name = p["name"].String();
count << uid << " " << name << endl;
}
4.
插入
void insert(const string &ns, BSONObj obj, int flags);
ns(IN)
:命名空间,db_name.collection_name
obj(IN)
:插入的列
flags(IN)
:详见API文档,默认填零即可
示例:
BSONObj insert = BSON("uid"<<10001<<"name"<<"skean1017");
pConn->insert(db+"."+collection, insert, 0);
其效果相当于:
insert into shool.student (uid, name) values (10001, “skean1017″);
5.
删除
void remove(const string &ns, Query query, bool justOne);
ns(IN)
:命名空间,db_name.collection_name
query(IN)
:查询条件
justOne(IN)
:是否只删除匹配的第一条
示例:
Query query = QUERY("name"<<"skean1017");
pConn->remove(db+"."+collection, query, true);
其效果相当于:
delete from shool.student where name=”skean1017″;
6.
修改
void update(const string &ns , Query query , BSONObj obj , bool upser , bool multi);
ns(IN)
:命名空间,db_name.collection_name
query(IN)
:查询条件
obj(IN)
:修改后的值
upser(IN)
:是否upser,如果不存在则插入记录
multi(IN)
:是否为符合文档
示例:
Query query = QUERY("uid"<<10001);
BSONObj obj = BSON("$set"<update(db+"."+collection, query, obj, false, false);
其效果相当于:
update shool.student set name=”habadog1203” where uid=10001;
mongodb
的api的异常处理
mongodb
为我们提供了
DBException异常类,如果有错误会进行抛出,我们可以通过try catch的方式捕捉该类错误,然后通过打印 what()显示错误详细信息.具体所在头文件:
assert_util.h.除了捕获mongo提供的异常信息,还需要捕获标准库的错误信息,最后有一个兜底的所有异常捕捉.
使用方法:
Try{
//写代码。。。。。。
}
catch( mongo::DBException& e ) {
printf("MONGO Exception(set): %s\n", e.what());
return -1;
}
catch (std::exception& e) {
printf("MONGO Exception(set): %s\n", e.what());
return -1;
}
catch (...){
printf(“MONGO Exception\n”);
return -1
}
一. insert
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace std;
using namespace mongo;
int main(int argc, char const *argv[])
{
string error;
/* 初始化对象,
第一参数:连接数据库超时是否重新连接
第二参数:默认为0
第个参数:设定超时的时间
*/
DBClientConnection conn(false, 0, 3);
// 连接数据库
if (!conn.connect("127.0.0.1:27017", error))
{
cout << "connect mongo err\n" << error << endl;
}
#if 0
/* 第一种方式
* 插入数据
第一个参数:数据库名.集合名
*/
BSONObjBuilder b;
b.append("_id", 1);
b.append("name", "test7");
BSONObj obj = b.obj();
conn.insert("test1.test", obj);
/*
第二种方式
*/
BSONObj obj;
obj = BSON("_id" << 2 << "name" << "test8");
conn.insert("test1.test", obj);
#endif
/*
第三种方式
*/
Query inobj("{_id:3, name:'test9', data:{age:6,sex:man}}");
conn.insert("test1.test", inobj.obj);
return 0;
}
二. select
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace std;
using namespace mongo;
int main(int argc, char const *argv[])
{
string error;
// 初始化
DBClientConnection conn(false, 0, 3);
// 连接数据库
if (!conn.connect("127.0.0.1:27017", error))
{
cout << "connect mongo err" << error << endl;
}
/*
@function:查询
@param1:数据库名.集合名
@param2:查询条件
@return : auto_ptr<DBClientCursor>
*/
auto_ptr<DBClientCursor> cursor = conn.query("test1.test", Query(""));
while (cursor->more())//为真next才有信息返回
{
// 返回一条文档
BSONObj obj = cursor->next();
//cout << obj << endl;
// 去掉 .0
//cout << obj.getIntField("_id") << endl;
//cout << obj["_id"] << endl;
// 只有字段
// cout << obj.getField("_id") << endl;
if (obj.hasElement("data"))
{
// 返回data文档的信息
BSONObj sobj = obj.getObjectField("data");
cout << sobj << endl;
cout << sobj.getIntField("age") << endl;
cout << sobj.getStringField("name") << endl;
}
}
return 0;
}
三. update
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace std;
using namespace mongo;
int main(int argc, char const *argv[])
{
string error;
DBClientConnection conn(false, 0, 3);
if (!conn.connect("127.0.0.1:27017", error))
{
cout << "connect mongo err" << error << endl;
return -1;
}
// 修改的字段数据
Query updobj("{$set:{name:'test9'}}");
/*
@func: 更新
@param2: 要修改的字段
@param3: 修改的数据
*/
conn.update("test1.test", Query("{_id:7}"), updobj.obj, false, false);
return 0;
}
四. remove
#include <iostream>
#include "mongo/client/dbclient.h"
using namespace std;
using namespace mongo;
int main(int argc, char const *argv[])
{
string error;
DBClientConnection conn(false, 0, 3);
if (!conn.connect("127.0.0.1:27017", error))
{
cout << "connect mongo err" << error << endl;
return -1;
}
/*
@func: remove
@param1: 数据库名.集合名
@param2: 删除的条件
@param3: 是否删除匹配多条
*/
conn.remove("test1.test", Query("{name:'test30'}"), false);
return 0;
}