19.MongoDB系列之批量更新写入Groovy版
Groovy作为脚本,比Java在数据处理中具有更高的灵活性
// 获取mongo连接略
....
def count = 0
for(Township town : townships) {
Document updateBson = new Document()
Document update = new Document()
update.put("city", town.city)
update.put("region", town.region)
update.put("name", town.name)
update.put("status", 1)
updateBson.append('$set', update)
Bson filterBson = Filters.eq("_id", new ObjectId(town.id))
UpdateOptions updateOptions = new UpdateOptions();
updateOptions.upsert(true)
UpdateOneModel updateOneModel = new UpdateOneModel(filterBson, updateBson, updateOptions);
writeModelList.add(updateOneModel)
if (writeModelList.size() == 5000) {
townshipConn.bulkWrite(writeModelList)
count += 5000
println(count)
writeModelList.clear()
}
}
if (writeModelList.size() > 0) {
townshipConn.bulkWrite(writeModelList)
writeModelList.clear()
}