tags:

views:

58

answers:

2

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)
+4  A: 

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

Amro
+1. The method does expect an array (or rather a vararg). Since Java5, there are now varargs, so from Java you can just call it with the DBObject directly. Does this mean varargs are not supported in the MATLAB Java bindings?
Thilo
As I recall, Java varargs are simply syntactic sugar for the array construct
Amro
@Amro: Very useful answer. Thanks a lot. I'm not so experienced with Java in MATLAB but learning.
yuk
+1  A: 

For the minor question about converting the list of collections use the toArray() method.

>> cList=cell(colls.toArray())

cList = 
  'foo'
  'system.indexes'
  'things'
Adrian
@Adrian: Thanks! Works great.
yuk

related questions