2013-07-11 35 views
0

所以情况如此:我有一个程序需要两个大的csv文件,找到差异,然后发送一个数组列表到一个方法,该方法应该用数组中的行更新mongodb。问题是更新正在持续进行。一个包含5000个更新的测试用例需要36分钟。这是正常的吗?用java驱动更新mongodb需要永久吗?

update(List<String> changes) - 方法是这样的:

mongoClient = new MongoClient(ip); 
db = mongoClient.getDB("foo"); 
collection = db.getCollection("bar"); 

//for each line of change 
for (String s : changes) { 
    //splits the csv-lines on ; 
    String[] fields = s.split(";"); 

    //identifies wich document in the database to be updated 
    long id = Long.parseLong(fields[0]); 
    BasicDBObject sq = new BasicDBObject().append("organizationNumber",id); 

    //creates a new unit-object, that is converted to JSON and then inserted into the database. 
    Unit u = new Unit(fields); 
    Gson gson = new Gson(); 
    String jsonObj = gson.toJson(u); 
    DBObject objectToUpdate = collection.findOne(sq); 
    DBObject newObject = (DBObject) JSON.parse(jsonObj); 

    if(objectToUpdate != null){ 
     objectToUpdate.putAll(newObject); 
     collection.save(objectToUpdate); 
} 
+0

您是否检查过服务器上的统计信息?看起来应该不会花费那么长时间才能有合理的配置。 – WiredPrairie

+0

@WiredPrairie我刚刚安装了它,我在找什么?你看,这是我第一次使用mongo。 – user2507863

+0

是否将'organizationNumber'编入索引? – WiredPrairie

回答

1

那是因为你正在采取额外的步骤来更新。 您不需要手动解析JSON,而只需单步执行“where”子句的更新,就无需执行查询 - 然后更新。

事情是这样的:

BasicDBObject query= new BasicDBObject().append("organizationNumber",id); 
Unit unit = new Unit(fields); 
BasicDBObject unitDB= new BasicDBObject().append("someField",unit.getSomeField()).append("otherField",unit.getOtherField()); 
collection.update(query,unitDB); 

query指定 “where” 子句和unitDB指定需要更新的领域。

+0

尽管这样可以改进算法,但由于某些其他原因,它似乎仍然非常慢。 5000在36分钟内找到并更新...这在合理的硬件上并不多。 – WiredPrairie

+0

你有太多索引吗?索引使插入速度明显变慢。尝试删除索引,如果你有他们,看看是否有任何区别。 – AntonioOtero