5
votes

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

3

3 Answers

7
votes

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.

4
votes

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

0
votes

In your last line, replace .distinct("messageNumber", Long.class) with .find().

distinct(String fieldName, Class<TResult> resultClass) returns only the unique values of the one field you request.

find() returns all documents of the collection with all of their fields.