我正在尝试更新每个文件"姓名"集合中的字段使用在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文件的错误吗?
答案 0 :(得分:1)
您处理光标的方式存在一些问题:
致电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点。