MongoDB频繁调用update操作的优化:
(1)创建索引字段,然后根据索引字段更新数据
注:updat匹配用的索引字段要选择整数类型的字段,千万别用字符串类型的字段作为索引,不信邪的话,你可以对比实测性能。
(2)采用批量提交的方式:
com.mongodb.client.MongoCollection.bulkWrite(List<? extends WriteModel<? extends TDocument>> requests)
List<UpdateOneModel<Document>> listOperations = new ArrayList<UpdateOneModel<Document>>();
for(Entry<String, MyPOJO> eitem:map.entrySet() )
{
Document item=eitem.getValue().toBson()
Document eq=new Document();
Document up=new Document();
eq.append("fieldid", item.get("fieldid"));
up.append("$set", item);
item.remove("_id");
listOperations.add(new UpdateOneModel<Document>(eq, up,ops));
}
BulkWriteResult bulkWriteResult = mongoClient.getCollection("dbname", "tablename").bulkWrite(listOperations);