Java,MongoDB:如何在迭代庞大的集合时更新每个对象? [英] Java, MongoDB: How to update every object while iterating a huge collection?
问题描述
我收集了大约100万条记录,每个记录有20个字段.我需要更新每个记录(文档)中的整数flag
字段,并随机分配1或2到此flag
字段.
在游标遍历整个集合时如何执行此操作?似乎第二次搜索MongoDB已经找到的对象只是为了能够更新它,这似乎不是一个好主意:
I have a collection of about 1 million records with 20 fields each. I need to update integer flag
field in every record (document) assigning randomly 1 or 2 to this flag
field.
How to do this while iterating cursor over the complete collection? It does not seem to be a good idea to search second time for object already found by MongoDB just to be able to update it:
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
...
coll.update(query,newObj)
}
} finally {
cursor.close();
}
如何有效地更新巨大的MongoDB集合的每个文档中具有不同值的字段?
How to update a field in every document of a huge MongoDB collection with different values efficiently?
推荐答案
您的方法基本上是正确的. 但是,我不会将这样的集合视为巨大的" 您可以从shell运行类似的东西:
Your approach is basically correct. However I wouldn't consider such a collection as "huge" You can run something similar from the shell:
coll.find({}).forEach(function (doc) {
doc.flag = Math.floor((Math.random()*2)+1);
coll.save(doc);
});
根据您的MongoDB版本,配置和负载,这可能需要几分钟到几小时的时间
Depending on your MongoDB version, configuration and load, this may take something between few minutes to several hours
如果要批量执行此更新,请在查询文档中使用某些条件,例如coll.find({"aFiled" : {$gt : minVal}, "aFiled" : {$lt : maxVal}})
If you want to perform this update in bulks, use some conditions in your query document, something such as coll.find({"aFiled" : {$gt : minVal}, "aFiled" : {$lt : maxVal}})
这篇关于Java,MongoDB:如何在迭代庞大的集合时更新每个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!