Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tailable Cursor example in Java using 3.0 driver?

Tags:

java

mongodb

Can someone please provide a complete tailable cursor example in Java? I am using the 3.0 driver and all examples appear to be 2.x. I have only mongo-java-driver-3.0.0.jar in my classpath. I want to get all documents as they are inserted in my capped collection.

//this does not work...
MongoCollection<BasicDBObject> col = database.getCollection(colName, BasicDBObject.class);
DBCursor cur = col.find().sort(new BasicDBObject("$natural", 1))
.addOption(Bytes.QUERYOPTION_TAILABLE)
.addOption(Bytes.QUERYOPTION_AWAITDATA);


// And this does not work...
BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
builder.add("messageType","STATUS_REQUEST");
DBObject searchQuery = builder.get();
DBObject sortBy = BasicDBObjectBuilder.start("$natural", 1).get();
BasicDBObjectBuilder builderForFields = BasicDBObjectBuilder.start();
DBObject fields = builderForFields.get();
DBCursor cursor = new DBCursor(col, searchQuery, fields, ReadPreference.primary()  );
cursor.sort(sortBy);
cursor.addOption(Bytes.QUERYOPTION_AWAITDATA);
cursor.addOption(Bytes.QUERYOPTION_TAILABLE);

//this does work but only returns the messageNumber field. I need the doc.
  MongoCursor<Long> c = database.getCollection(colName).distinct("messageNumber", Long.class).iterator();

I see that the MongoCursor interface was added in 3.0. What is that for and does it replace DBCursor?

Thanks a lot

like image 370
Andrew Avatar asked May 04 '15 11:05

Andrew


2 Answers

A bit late to the party, but in case you still need help:

find(query).projection(fields).cursorType(CursorType.TailableAwait).iterator();

That code applies to the MongoCollection class.

CursorType is an enum and it has the following values:

Tailable
TailableAwait

Corresponding to the old DBCursor addOption Bytes types:

Bytes.QUERYOPTION_TAILABLE
Bytes.QUERYOPTION_AWAITDATA

I hope that helps.

like image 144
Emil Burzo Avatar answered Sep 26 '22 23:09

Emil Burzo


This is what you might be looking for - EVENT Streaming in MongoDB 3.0.* using new api i.e. 3.0.2

Document query = new Document(); \\here use { indexedField: { $gt: <lastvalue> } index is not used(except for auto deleting documents) but created in capped collection
Document projection = new Document();
MongoCursor<Document> cursor= mongocollection.find(query).projection(projection).cursorType(CursorType.TailableAwait).iterator();  //add .noCursorTimeout(true) here to avoid timeout if you are working on big data

while (cursor.hasNext()){
    Document doc = cursor.next();
    //do what you want with doc
}

This way mongo cursor will check for new entries in capped collection

like image 31
Tushar Avatar answered Sep 25 '22 23:09

Tushar