2016-11-17 144 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(不是某些特定领域)就像保存一样。