开发者

Connecting to MongoDB from MATLAB

开发者 https://www.devze.com 2023-01-19 07:46 出处:网络
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'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

javaaddpa开发者_运维技巧th('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)


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


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


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

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

cList = 
  'foo'
  'system.indexes'
  'things'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号