An accessible example of a cursor in Java using Driver 3.0?
Can anyone provide a complete example of using a cursor in Java? I am using driver 3.0 and all examples look like 2.x. I only have mongo-java-driver-3.0.0.jar in my classpath. I want to get all documents as they are inserted into my bounded 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 can see that the MongoCursor interface was added in 3.0. What does this mean and will replace DBCursor?
Thank you so much
source to share
A bit late for the party, but if you still need help:
find(query).projection(fields).cursorType(CursorType.TailableAwait).iterator();
This code belongs to the class MongoCollection
.
CursorType is an enumeration and has the following meanings:
Tailable
TailableAwait
As per the old DBCursor addOption Bytes types:
Bytes.QUERYOPTION_TAILABLE
Bytes.QUERYOPTION_AWAITDATA
I hope this helps.
source to share
This is what you might be looking for - EVENT Streaming in MongoDB 3.0. * using the new api ie 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 the mongo cursor will check for new entries in the private collection
source to share
On your last line, replace .distinct("messageNumber", Long.class)
with .find()
.
distinct(String fieldName, Class<TResult> resultClass)
returns only the unique values ββof the single field you are requesting.
find()
returns all documents in a collection with all their fields.
source to share