2016-11-17 140 views
2

從1.9.0.RELEASE的spring-data-mongodb支持批量更新。Spring數據mongo批量更新

BulkOperations ops = template.bulkOps(BulkMode.UNORDERED, Match.class); 
for (User user : users) { 
    Update update = new Update(); 
    ... 
    ops.updateOne(query(where("id").is(user.getId())), update); 
} 
ops.execute(); 

mongoTemplate具有名爲void save(Object objectToSave)的函數;我想插入/更新整個記錄,但不是某些特定的字段。有什麼方法或功能可以讓Update類無效嗎?

也許是這樣的..?

BulkOperations ops = template.bulkOps(BulkMode.UNORDERED, Match.class); 
for (User user : users) { 
    ... 
    ops.save(query(where("id").is(user.getId())), user); 
} 
ops.execute(); 

回答

0

刪除和插入將是你可以選擇的選項,但需要你選擇的任何故障的情況下,這個選擇之前採取備份您的數據。

2

看來,UPSERT它不是在Spring數據MongoDB的批量操作支持(查詢的查詢,Object對象)。

但是我們可以使用Update.fromDBObject方法來生成從更新對象DBOBJECT

BulkOperations bulkOps = mongoOperations.bulkOps(BulkOperations.BulkMode.ORDERED, entityInformation.getJavaType()); 

    // add "save" operation for each entity 
    MongoConverter converter = mongoOperations.getConverter(); 
    ConversionService conversionService = converter.getConversionService(); 
    com.mongodb.DBObject dbObject; 
    for (S entity : entities) { 
     if (entityInformation.isNew(entity)) { // --- if NEW entity, then generate id and INSERT --- 

      // generate NEW id 
      ID id = conversionService.convert(new ObjectId(), entityInformation.getIdType());     
      entity.setId(id); 
      // insert 
      bulkOps.insert(entity); 

     } else { // --- if EXISTING entity, then UPSERT --- 

      // convert entity to mongo DBObject 
      dbObject = new BasicDBObject(); 
      // NULL fields will NOT BE UPDATED - will be ignored when converting an entity to a {@link com.mongodb.DBObject} 
      // and thus they will not be added to the {@link Update} statement. 
      converter.write(entity, dbObject);     
      // upsert 
      bulkOps.upsert(new Query(Criteria.where(UNDERSCORE_ID).is(dbObject.get(UNDERSCORE_ID))), 
          Update.fromDBObject(new BasicDBObject("$set", dbObject))); 
     } 
    } 
    // execute bulk operations 
    bulkOps.execute(); 
0

你可以試試這個:

BulkOperations ops = mongoOps.bulkOps(BulkMode.<ordered/unordered>,<your ob>.class); 
loop on your batch { 
    Update update = Update.fromDBObject(
     BasicDBObjectBuilder.start("$set", <your ob>).get() 
    ); 
    ops.upsert(query(where("").is(<your ob>.something())), update); 
} 
ops.execute(); 

這將更新整個pojo(不是某些特定領域)就像保存一樣。