16 Oct 2010 ebf   » (Master)

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! :)


<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 />
<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 />

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!