一,mongodb-api 介绍
1, 连接类
DBClientConnection(bool _autoReconnect=false, DBClientReplicaSet* cp=0, double so_timeout=0)
参数:
- _autoReconnect 自动重连
- cp 副本集使用参数,可以不用关心
- so_timeout 超时时间 单位 秒
2,连接函数
virtual bool connect(const char * hostname, string& errmsg)
参数:
- hostname 主机名 ip:端口 默认端口 27017
- errmsg 错误信息 传出
返回值:
false 代表失败
true 代表成功
DBClientConnection 继承与 DBClientBase ,该类内部包含增删改查四个接口
进行增删改查操作
通过api删除文档
删除文档
virtual void remove( const string &ns , Query q , bool justOne = 0 );
○ ns 集合名,填法 库名.集合名
○ q 删除条件 Query 是一个类
○ justOne 是否删除一条,默认false
class Query {
public:
BSONObj obj;
Query() : obj(BSONObj()) { }
Query(const BSONObj& b) : obj(b) { }
Query(const string &json);
Query(const char * json);
增加文档
virtual void insert( const string &ns , BSONObj obj , int flags=0);
○ ns 库名.集合名
○ obj 要插入的内容,核心对象,需要BSONObjBuilder构造, append函数 BSONObj obj()
#include "mongo/client/dbclient.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/client/dbclientinterface.h"
#include <set>
#include <list>
#include <string>
#include <vector>
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/stringdata.h"
#include "mongo/bson/util/atomic_int.h"
#include "mongo/bson/util/builder.h"
#include <iostream>
#include <string>
//命令空间
using namespace mongo;
using namespace std;
#define REMOVE 0
#define INSERT 1
int main(int argc, char *argv[])
{
//创建连接类mongdb
DBClientConnection conn(false, 0, 3);
std::string errmsg;
//连接mongdb virtual bool connect(const char * hostname, string& errmsg)
if (!conn.connect("localhost:27017", errmsg))
{
cout << "connection error " << errmsg << endl;
return -1;
}
#if REMOVE
//删除数据
//virtual void remove( const string &ns , Query q , bool justOne = 0 );
Query q("{name:'王蓉'}");
//参数一:
conn.remove("songli.songli", q, false);
#endif // REMOVE
#if INSERT
//插入数据
//virtual void insert( const string &ns , BSONObj obj , int flags=0);
BSONObjBuilder builder;
builder.append("id", 7);
builder.append("name", "杨艳2");
builder.append("age", 23);
conn.insert("songli.songli", builder.obj());
BSONObjBuilder b;
b << "id" << 6 << "name" << "王盼盼" << "age" << 23;
conn.insert("songli.songli", b.obj());
//virtual void insert( const string &ns , BSONObj obj , int flags=0);
conn.insert("songli.songli", BSON("id" << 9 << "name" << "巍盼盼" << "age" << "23"));
//
Query q("{id:10, name:'陈丽', age: 23}");
conn.insert( "songli.songli", q.obj);
#endif // INSERT
查询语句
virtual BSONObj findOne(const string &ns, const Query& query, const BSONObj *fieldsToReturn = 0, int queryOptions = 0);
//Query find("db.songli.find({name:'陈丽'})");
//BSONObj obj = conn.findOne("songli.songli", find.obj);
//cout << obj.numStr(1) << endl;
printf("connection ok\n");
return 0;
}
查询
修改文档
void update( const string &ns,
Query query,
BSONObj obj,
bool upsert = false, bool multi = false );
○ ns 库名.集合名
○ query 查询条件
○ obj 要修改的内容
实现查询文档
virtual auto_ptr query(const string &ns, Query query=Query(), int nToReturn = 0, int nToSkip = 0,
const BSONObj *fieldsToReturn = 0, int queryOptions = 0 , int batchSize = 0 )
○ ns 库名.集合名
○ query 查询条件
○ nToReturn 返回记录数
○ nToSkip 跳过记录数
○ fieldsToReturn 返回的字段
○ queryOptions 查询选项
○ batchSize 批量大小
auto_ptr auto_ptr是智能指针,自动释放DBClientCursor内存区域
关注
DBClientCursor 类
可以先调用more 判断是否有next ,得到BSONObj next(); 对象
问题的核心就是如何解析 BSONObj
解析 BSONObj的方式 getFiled 获得 BSONElement对象 ,这个对象各种转换函数得到具体的value
可以先用hasField判断一下字段是否存在
//g++ -o testmongo testmongo.cpp -lmongoclient -lboost_thread -lboost_filesystem -lboost_program_options -L/home/itcast/driver/boost/lib -L/home/itcast/driver/mongo/lib -I/home/itcast/driver/mongo/include -I/home/itcast/driver/boost/include
#include <iostream>
#include "mongo/client/dbclient.h"
char dbhost[20]="localhost";
using namespace mongo;
using namespace std;
void printIfAge(DBClientConnection& c, int age) {
auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", QUERY( "age" << age ).sort("name") );
while( cursor->more() ) {
BSONObj p = cursor->next();
cout << p.getStringField("name") << endl;
}
}
void run() {
DBClientConnection c;
c.connect(dbhost);
cout << "connected ok" << endl;
BSONObj p = BSON( "name" << "Joe" << "age" << 33 );
c.insert("tutorial.persons", p); /**< 向person表中插入数据 */
p = BSON( "name" << "Jane" << "age" << 40 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Abe" << "age" << 33 );
c.insert("tutorial.persons", p);
p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" );
c.insert("tutorial.persons", p);
c.ensureIndex("tutorial.persons", fromjson("{age:1}"));
cout << "count:" << c.count("tutorial.persons") << endl; /**< 显示person表中的数据数目 */
auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj());
while( cursor->more() ) {
cout << cursor->next().toString() << endl;
}
cout << "\nprintifage:\n";
printIfAge(c, 33);
}
int main(int argc,char *argv[]) {
if(argc == 2)
{
memset(dbhost,0x00,sizeof(dbhost));
strcpy(dbhost,argv[1]);
printf("connect to dbhost:[%s]\n",dbhost);
}
else
{
printf("connect to dbhost:[%s]\n",dbhost);
printf("if you need to connet to remote service,please input ip!\n");
}
try {
run();
}
catch( DBException &e ) {
cout << "caught " << e.what() << endl;
}
return 0;
}