我正在尝试使用在 Java Mongo 驱动程序的 FindIterable 接口(interface)中定义的 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.hasNext()
的单次迭代多次调用iterator.next()
。这是有问题的,您最终会在光标耗尽时调用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 点的基础上构建的。
关于java - Mongo JAVA driver-3.6 iterator() 一次又一次迭代单个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970640/