Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to MongoDB from MATLAB

Tags:

mongodb

matlab

I'm trying to use MongoDB with MATLAB. Although there is no supported driver for MATLAB, there is one for Java. Fortunately I was able to use it to connect to db, etc. I downloaded the latest (2.1) version of jar-file and install it with JAVAADDPATH. Then I tried to follow the Java tutorial.

Here is the code

javaaddpath('c:\MATLAB\myJavaClasses\mongo-2.1.jar')

import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;

m = Mongo(); % connect to local db
db = m.getDB('test'); % get db object
colls = db.getCollectionNames(); % get collection names
coll = db.getCollection('things'); % get DBCollection object

doc = BasicDBObject();
doc.put('name', 'MongoDB');
doc.put('type', 'database');
doc.put('count', 1);
info = BasicDBObject();
info.put('x', 203);
info.put('y', 102);
doc.put('info', info);
coll.insert(doc);

Here is where I stacked. coll supposed to be DBCollection object, but actually is object of com.mongodb.DBApiLayer$MyCollection class. So the last command returns the error:

??? No method 'insert' with matching signature found for class 'com.mongodb.DBApiLayer$MyCollection'.

In the tutorial the coll variable is created explicitly as DBCollection object:

DBCollection coll = db.getCollection("testCollection")

Am I doing something wrong in MATLAB? Any ideas?

Another minor question about colls variable. It's com.mongodb.util.OrderedSet class and contains list of names of all collections in the db. How could I convert it to MATLAB's cell array?


Update: In addition to Amro's answer this works as well:

wc = com.mongodb.WriteConcern();
coll.insert(doc,wc)
like image 383
yuk Avatar asked Oct 07 '10 22:10

yuk


2 Answers

A quick check:

methodsview(coll)        %# or: methods(coll, '-full')

shows that it expects an array:

com.mongodb.WriteResult  insert(com.mongodb.DBObject[])

Try this instead:

doc(1) = BasicDBObject();
doc(1).put('name', 'MongoDB');
doc(1).put('type', 'database');
...
coll.insert(doc);

Note: If you are using Java in MATLAB, I suggest you use the CheckClass and UIInspect utilities by Yair Altman

like image 109
Amro Avatar answered Sep 22 '22 19:09

Amro


There is now a driver built expressly to connect MongoDB and Matlab. It is built on top of the mongo-c-driver. Source can be found on github:

https://github.com/gerald-lindsly/mongo-matlab-driver

like image 40
Dan P Avatar answered Sep 18 '22 19:09

Dan P