MongoDBAfter an article on the use of SqlLite with Matlab, here is another way to interact with database, a NoSQL database powered by MongoDB.

First of all, you have to install MongoDB on your computer. For my part, I used the Windows installer which you could find here. For convenience, I also configure it to use the windows service so that the server is easier to start and stop automatically.

After installing MongoDB server, to interact with Matlab, you'll need a driver. You could use the Java one or the .NET one. I've tried both, but I'll only present the .NET one (download it here), also there is no big difference between them. So let's start.

The use of the MongoDB driver is really simple as you'll see. First we need to declare the assembly in Matlab :  NET.addAssembly('%PATH_TO_DRIVER%\MongoDB.Driver.dll');

You could also use the namespace with an import call to the MongoDB.Driver.*, but I prefer writing the whole path to show where to look for help for the classes I use. We need then to connect to the server by instantiating a mongo client and "open" or "create" a new collection of documents:

Now, we connected to the database and retrieved or created a collection named "collection". I invite you to read the documentation to see how to manipulate collections and documents. For instance, it is really simple to clear a collection by calling the method  collection.RemoveAll();

We have established a connection to a database and we have access to a collection. We can now populate the collection with documents. The beauty of NoSQL databases is that no schema or table is needed. MongoDB is a document based database so you can serialize anything you want in it. For more advanced use, you can even serialize and deserialize you own .NET class. This is very convenient but also limiting because it is like declaring a schema or a table just as you would do with SQL databases. So, to populate a MongoDB Database, we need to create a BsonDocument (kind of enhanced JSON document), and add key-value pairs to it just as you would do with JSON elements

As you can see, a BsonDocument is a collection of BsonElement which are pairs of a string (the property name) and a BsonType (string, double, bool, etc. or your own class !). And that's all ! Well, we are not finished because we need to save (or insert, or update) this document into the database, which is done by

The insertion is simply a call to the 'Insert' method. Here, I also used a WriteConcern which tells the server how to write the data to the database. The 'SAFEMODE' ensure that your data is well written in the database. I did that to ensure that MongoDB server and Matlab performance difference is not the bottleneck because I already saw that my data were not well written.

And that's it ! We've now populated our database and we'll see in a next post how to retrieve those documents and how we can play with them with map-reduce commands, queries, or simply document reading.