2015-05-04 71 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