Mongodb c++ API的测试和封装

安装好c++的驱动后,对API进行了测试。官方api:https://mongodb.github.io/mongo-cxx-driver/api/legacy-1.0.0/

参考的代码博文:https://www.cnblogs.com/edgarli/archive/2013/04/27/3046699.html

往数据库中保存数据必须创建BSONObj类的对象,BSONObj下各组件都可以叫做BSONElement对象。使用BSONObjBuilder构造各种BSON对象,用BSONObjIterator来遍历BSON对象。

BSONObj bsonEmpty = BSONObj();
BSONObj b = BSON("name"<<"xyj"<<"age"<<18);

insertDocument(&conn,collection,b);
//removeDocument(&conn,collection,b);

BSONObj data = updateData(&conn,collection,b);
string name = data.getStringField("name");
int age = data.getIntField("age");

BSONObj  resetAge = BSONObjBuilder().appendElements(b).append("sex","male").obj();

//查询符合条件的元组

auto_ptr<DBClientCursor> cursor = conn.query( collection , BSONObj() );
int count = 0;
while (cursor->more())
{
count++;
BSONObj temp = cursor.next();
}

GridFS和GridFile类

一切都不如看源码来的实在,API也凑合。

GridFile类:存储于mongodb里的文件数据类,官方注释: wrapper for a file stored in the Mongo database。用于获取相关文件的内部数据,下载,判断是否存在等

GridFS类:mongodb的文件操作类,官方注释:GridFS is for storing large file-style objects in MongoDB.。用于GridFS数据库的连接,文件的上传、查找、删除等

附上相关代码:

string dbName = "PDFS";
string fileName = "D:\PPT.pdf";
string remoteName = "up.pdf";
GridFS gf(conn,dbName);
gf.storeFile(fileName,remoteName);

GridFile gFile = gf.findFile(remoteName);
bool flag = gFile.exists();
gFile.write("D:\down.pdf");

原文地址:https://www.cnblogs.com/hanmolabi/p/8120792.html