Notes on GridFS and MongoDB
Today we made several tests with MongoDB’s GridFS. And, as simple as it is, we had a hard time trying to find detailed documentation and samples on C++ of this monster (on a good way
).
After brushing some bits, groking headers and a very thorough analysis of the C++ driver source code, we got a simple code snippet that stores an arbitrary file on GridFS, and changes its metadata. This is the sample that worked – if you have any suggestions, please comment! ![]()
Enjoy!
<br />
...<br />
#include "mongo/client/dbclient.h"<br />
#include "mongo/client/gridfs.h"</p>
<p>using namespace mongo;</p>
<p>...<br />
// The file's full path<br />
m_NomeArquivo = ...;<br />
QFileInfo info(m_NomeArquivo);</p>
<p>...<br />
DBClientConnection c;<br />
// local connection to MongoDB.<br />
c.connect("localhost");</p>
<p>// Here we "map" GridFS with the prefix we desire<br />
GridFS gfs = GridFS(c, "gridfs", "myfiles");<br />
BSONObj ret = gfs.storeFile(m_NomeArquivo.toStdString(), info.fileName().toStdString());<br />
BSONObjBuilder b;<br />
b.appendElements(ret);<br />
// Here we can add any additional information we want<br />
b.append("fileInserted", "0001");<br />
BSONObj o = b.obj();</p>
<p>// And now we update the document on MongoDB.<br />
c.update("gridfs.myfiles.files", BSON("filename" << retorno.getField("filename")), o, false, false);<br />
Syndicated 2010-10-16 00:44:24 (Updated 2010-10-25 22:46:40) from #include "ebf.h"
