Spring Data MongoDB 批量操作中似乎不支持upsert(Query query, Object object) 。
但是,我们可以使用Update.fromDBObject方法从DBObject生成Update对象:
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();