mongodb的c++接口的说明

mongodb c++ 接口说明

说明:
IN表示输入参数;
OUT表示输出参数;

(1)构造函数:
DBClientConnection(bool auto_connect, 0, double so_timeout);
auto_connect(IN):连接失败后自动重连
so_timeout(IN):非连接超时,tcp的读写超时

(2)连接mongo:
bool connect(string server, &string errmsg);
返回值:成功/失败
server(IN):连接的服务器
errmsg(OUT):出错信息

示例:

?
1
2
3
4
5
6
7
bool auto_connect = true ;
double so_timeout = 3;
string host = "127.0.0.1" ;
string port = "3003" ;
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:返回结果条数,相当于mysql中的limit
nToSkip:跳过的结果条数,相当于mysql中的offset
fieldsToReturn:返回列集合
queryOptions:详见QueryOptions这个枚举,填0即可
batchSize:未说明

示例:

?
1
2
3
4
5
6
7
8
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;

对结果集的操作:

?
1
2
3
4
5
6
7
8
9
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文档,默认填零即可

示例:

?
1
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):是否只删除匹配的第一条

示例:

?
1
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):是否为符合文档

示例:

?
1
2
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的c++接口的说明)