我正在尝试使用Java Mongo驱动程序的FindIterable接口中定义的iterator()更新集合中的每个文档“名称”字段。迭代器上的next()函数应该给我下一个BSON对象,但实际上,它是在同一个对象上进行迭代。
public void func1(FindIterable<org.bson.Document> documents, MongoCollection<org.bson.Document> coll_name) {
/*
* This function will run until all the documents in a collection aren't retrieved.
* */
try {
while (documents.iterator().hasNext()) {
coll_name.updateOne(eq("_id", documents.iterator().next().get("_id")), new org.bson.Document("$set", new org.bson.Document("Name", getName((String) documents.iterator().next().get("NameSource")))));
System.out.println("Document _id " + documents.iterator().next().get("_id") + " updated.....! in time : " + df.format(dater));
}
}catch (Exception ex){
System.out.println(" ~~~~~~~~~~~Was not able to getName() & update document~~~~~~~~~~~~~~~~~~");
System.out.println(ex.getMessage()) ;
} finally {
documents.iterator().close();
}
}
调用该函数:
FindIterable<org.bson.Document> FRESH_docs = coll_name.find(exists("Text", false)).noCursorTimeout(true);
int flag = 1;
try{
func1(FRESH_docs, coll_name, flag);
}catch (Exception ex){
System.out.println(" ~~~~~~~~~~~call to func1() failed for FRESH_docs ~~~~~~~~~~~~~~~~~~");
System.out.println(ex.getMessage());
}
输出为:
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:42.876
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:42.902
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:42.930
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:42.958
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:42.984
Document _id 4713205 updated.....! in time : 2017-12-25 08:56:43.012
.....
我删除了日期时间打印机以进行干净的代码评估。有人能建议我在同一BSON文档上进行迭代时会犯什么错误吗?
处理游标的方式存在一些问题:
打电话documents.iterator()
一次。查看源代码后,似乎在此调用上获得了一个新的迭代器。因此,您可能每次想要进行新迭代时都重新开始练习:
MongoCursor<org.bson.Document> iterator = documents.iterator();
while (iterator.hasNext()) {
// process
}
您正在iterator.next()
多次调用一次迭代监视iterator.hasNext()
。这是有问题的,next()
游标被释放时您最终会调用。建议更改:
//Call next once in the iteration and reuse the doc:
while (iterator.hasNext()) {
org.bson.Document nextDocument = iterator.next();
coll_name.updateOne(eq("_id", nextDocument.get("_id")), new org.bson.Document("$set", new org.bson.Document("Name", getName((String) nextDocument.get("NameSource")))));
System.out.println("Document _id " + nextDocument.get("_id") + " updated.....! in time : " + df.format(dater));
}
如您所见,第2点建立在第1点上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句