简体   繁体   中英

Matlab delete all documents from MongoDB collection via Java driver

I'm in the process of writing a cleanup routine for a mongodb collection for a unit test via the java driver (i tried the "native" matlab driver but the documentation is, well, scarce).

I can get a connection going (at least i think i can), but i'm stuck at invoking the remove method on a DBCollection object.

I'm running the following code:

javaaddpath(pathToJarFile)

import com.mongodb.*;

mongoClient = MongoClient(mHost);
mongoConn = mongoClient.getDB(dbName);
auth = mongoConn.authenticate(user,password);

events = mongoConn.getCollection('events');

events.remove();

On the last line i get the error

No method 'remove' with matching signature found for class 'com.mongodb.DBCollectionImpl'.

Since i know that the ´remove´ method exists for the DBCollection class, i'm a bit at a loss currently.

Any help would be appreciated. Note that i'm essentially illiterate when it comes to OOP :-S


Edit:

Please note that i also tried

events.remove({});

which results in the same error message.

According to the API documentation of DBCollection.remove , you must provide a DBObject that simply specifies the deletion criteria. It further says to pass an empty document to delete all documents in the collection. At least you must provide an argument.

According to the documentation on how to remove all documents from a collection , you simply pass the argument {} indicating an empty document to that method. So you must call

events.remove( {} );

To answer your question in the comments: The argument must be a DBObject that describes the remove criteria. A cursor is not such a document.

It seems that {} isn't passed correctly by MATLAB, so creating an empty document and passing it to remove does indeed work.

The working code looks like this:

javaaddpath(pathToJarFile)

import com.mongodb.*;

mongoClient = MongoClient(mHost);
mongoConn = mongoClient.getDB(dbName);
auth = mongoConn.authenticate(user,password);

events = mongoConn.getCollection('events');

empty = BasicDBObject();
events.remove(empty);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM