2015-05-04 73 views
3

有人可以在Java中提供完整的可放大遊標示例嗎?我使用3.0驅動程序,所有示例都顯示爲2.x.我的類路徑中只有mongo-java-driver-3.0.0.jar。我想要獲取所有文檔,因爲它們插入到我的封面集合中。使用3.0驅動程序的Java中的Tailable Cursor示例?

//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(); 

我看到MongoCursor接口是在3.0中添加的。這是什麼和它取代DBCursor?

非常感謝

回答

0

在你的最後一行,與.find()更換.distinct("messageNumber", Long.class)

distinct(String fieldName, Class<TResult> resultClass)只返回您請求的一個字段的唯一值。

find()返回集合的所有文檔及其所有字段。

+0

此檢查新條目似乎並沒有使它成爲可能的。這是如何在V3中完成的?之前有DBCursor.addOption(...) – Andrew

3

有點遲到了,但如果你仍然需要幫助:

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

該代碼適用於MongoCollection類。

的CursorType是一個枚舉,它具有以下值:

Tailable 
TailableAwait 

對應於舊DBCursor addOption字節類型:

Bytes.QUERYOPTION_TAILABLE 
Bytes.QUERYOPTION_AWAITDATA 

我希望幫助。

3

這就是你可能會尋找 - 在MongoDB中3.0事件流*使用新的API,即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 
} 

這樣蒙戈光標將在加蓋收集

+0

是否有光標超時? – user320550

+0

@ user320550存在默認超時。爲了避免超時此添加到光標 - .noCursorTimeout(真) 所以現在 MongoCursor 光標= mongocollection.find(查詢).projection(投影).noCursorTimeout(真).cursorType(CursorType.TailableAwait).iterator (); –

+0

謝謝。你是如何實踐這個的?你是否有一個單獨的線程繼續運行這個代碼來查找mongo oplog的新條目? – user320550