下面列出了com.mongodb.client.result.UpdateResult#getModifiedCount ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public int updateParticipant(final HmilyTransaction hmilyTransaction) {
Query query = new Query();
query.addCriteria(new Criteria("transId").is(hmilyTransaction.getTransId()));
Update update = new Update();
try {
update.set("contents", objectSerializer.serialize(hmilyTransaction.getHmilyParticipants()));
} catch (HmilyException e) {
e.printStackTrace();
}
final UpdateResult updateResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
if (updateResult.getModifiedCount() <= 0) {
throw new HmilyRuntimeException("update data exception!");
}
return ROWS;
}
@Override
public Boolean updateRetry(final String id, final Integer retry, final String appName) {
if (StringUtils.isBlank(id) || StringUtils.isBlank(appName) || Objects.isNull(retry)) {
return Boolean.FALSE;
}
final String mongoTableName = RepositoryPathUtils.buildMongoTableName(appName);
Query query = new Query();
query.addCriteria(new Criteria("transId").is(id));
Update update = new Update();
update.set("lastTime", DateUtils.getCurrentDateTime());
update.set("retriedCount", retry);
final UpdateResult updateResult = mongoTemplate.updateFirst(query, update,
MongoAdapter.class, mongoTableName);
if (updateResult.getModifiedCount() <= 0) {
throw new HmilyRuntimeException("更新数据异常!");
}
return Boolean.TRUE;
}
@Override
public <T> T merge(final T entity, final InsertOneOptions options) {
final Object id = mapper.getId(entity);
if (id == null) {
throw new MappingException("Could not get id for " + entity.getClass().getName());
}
final Document document = mapper.toDocument(entity);
document.remove("_id");
final Query<T> query = (Query<T>) find(entity.getClass()).filter(eq("_id", id));
if (!tryVersionedUpdate(entity, mapper.getCollection(entity.getClass()), options)) {
UpdateResult execute = query.update(UpdateOperators.set(entity))
.execute(new UpdateOptions()
.clientSession(findSession(options))
.writeConcern(options.writeConcern()));
if (execute.getModifiedCount() != 1) {
throw new UpdateException("Nothing updated");
}
}
return query.first();
}
/**
* 更新
*
* @param dbName
* @param collectionName
* @param filter
* @param document
* @return
*/
public boolean updateOne(String dbName, String collectionName, Document filter, Document document) {
if (filter != null && filter.size() > 0 && document != null) {
UpdateResult result = mongoClient.getDatabase(dbName).getCollection(collectionName)
.updateOne(new Document(filter), new Document("$set", new Document(document)));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
return false;
}
/**
* 通过_id更新
*
* @param dbName
* @param collectionName
* @param _id
* @param document
* @return
*/
public boolean updateById(String dbName, String collectionName, String _id, Document document) {
ObjectId objectId = new ObjectId(_id);
Bson filter = Filters.eq("_id", objectId);
UpdateResult result = getDatabase(dbName).getCollection(collectionName).updateOne(filter,
new Document("$set", document));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
@Override
public int updateStatus(final String id, final Integer status) {
Query query = new Query();
query.addCriteria(new Criteria("transId").is(id));
Update update = new Update();
update.set("status", status);
final UpdateResult updateResult = template.updateFirst(query, update, MongoAdapter.class, collectionName);
if (updateResult.getModifiedCount() <= 0) {
throw new HmilyRuntimeException("update data exception!");
}
return ROWS;
}
public SyncUpdateResult execute(@Nullable final CoreStitchServiceClient service) {
final UpdateResult localResult = this.dataSynchronizer.updateOne(
namespace,
filter,
update,
new UpdateOptions().upsert(this.syncUpdateOptions.isUpsert()));
return new SyncUpdateResult(
localResult.getMatchedCount(),
localResult.getModifiedCount(),
localResult.getUpsertedId()
);
}
public SyncUpdateResult execute(@Nullable final CoreStitchServiceClient service) {
final UpdateResult localResult = this.dataSynchronizer.updateMany(
namespace,
filter,
update,
new UpdateOptions().upsert(this.syncUpdateOptions.isUpsert()));
return new SyncUpdateResult(
localResult.getMatchedCount(),
localResult.getModifiedCount(),
localResult.getUpsertedId()
);
}
@Override
long executeQuery(int threadId, long threadRunCount, long globalRunCount, long selectorId, long randomId){
final Document doc = new Document("$set", new Document(RANDOM_LONG, randomId))
.append("$inc", new Document(VERSION, 1));
final UpdateResult res = THREAD_RUN_COUNT.equals(queriedField)?mongoCollection.updateMany(eq(queriedField, selectorId), doc)
:ID.equals(queriedField)?mongoCollection.updateOne(eq(queriedField, selectorId), doc):null;
return res!=null?res.getModifiedCount():0l;
}
private <T> OpResult addOrReplace(MongoCollection<Document> collection, T t) {
BsonDocument filter = new BsonDocument();
if (t instanceof StreamDefinition) {
filter.append("streamId", new BsonString(MetadataUtils.getKey(t)));
} else if (t instanceof AlertPublishEvent) {
filter.append("alertId", new BsonString(MetadataUtils.getKey(t)));
} else {
filter.append("name", new BsonString(MetadataUtils.getKey(t)));
}
String json = "";
OpResult result = new OpResult();
try {
json = mapper.writeValueAsString(t);
UpdateOptions options = new UpdateOptions();
options.upsert(true);
UpdateResult ur = collection.replaceOne(filter, Document.parse(json), options);
// FIXME: could based on matched count do better matching...
if (ur.getModifiedCount() > 0 || ur.getUpsertedId() != null) {
result.code = 200;
result.message = String.format("update %d configuration item.", ur.getModifiedCount());
} else {
result.code = 500;
result.message = "no configuration item create/updated.";
}
} catch (Exception e) {
result.code = 500;
result.message = e.getMessage();
LOG.error("", e);
}
return result;
}
@Override
public void update(final RyaDetails oldDetails, final RyaDetails newDetails)
throws NotInitializedException, ConcurrentUpdateException, RyaDetailsRepositoryException {
// Preconditions.
requireNonNull(oldDetails);
requireNonNull(newDetails);
if(!newDetails.getRyaInstanceName().equals( instanceName )) {
throw new RyaDetailsRepositoryException("The instance name that was in the provided 'newDetails' does not match " +
"the instance name that this repository is connected to. Make sure you're connected to the" +
"correct Rya instance.");
}
if(!isInitialized()) {
throw new NotInitializedException("Could not update the details for the Rya instanced named '" +
instanceName + "' because it has not been initialized yet.");
}
if(oldDetails.equals(newDetails)) {
return;
}
final MongoCollection<Document> col = db.getCollection(INSTANCE_DETAILS_COLLECTION_NAME);
final Document oldObj = MongoDetailsAdapter.toDocument(oldDetails);
final Document newObj = MongoDetailsAdapter.toDocument(newDetails);
final UpdateResult result = col.replaceOne(oldObj, newObj, new ReplaceOptions());
//since there is only 1 document, there should only be 1 update.
if(result.getModifiedCount() != 1) {
throw new ConcurrentUpdateException("Could not update the details for the Rya instance named '" +
instanceName + "' because the old value is out of date.");
}
}
static MongoClientUpdateResult toMongoClientUpdateResult(UpdateResult updateResult) {
return updateResult.wasAcknowledged() ? new MongoClientUpdateResult(updateResult.getMatchedCount(), convertUpsertId(updateResult.getUpsertedId()), updateResult.getModifiedCount()) : null;
}
private <T> boolean tryVersionedUpdate(final T entity, final MongoCollection collection, final InsertOneOptions options) {
final MappedClass mc = mapper.getMappedClass(entity.getClass());
if (mc.getVersionField() == null) {
return false;
}
MappedField idField = mc.getIdField();
final Object idValue = idField.getFieldValue(entity);
final MappedField versionField = mc.getVersionField();
Long oldVersion = (Long) versionField.getFieldValue(entity);
long newVersion = oldVersion == null ? 1L : oldVersion + 1;
ClientSession session = findSession(options);
if (newVersion == 1) {
try {
updateVersion(entity, versionField, newVersion);
if (session == null) {
options.prepare(collection).insertOne(entity, options.getOptions());
} else {
options.prepare(collection).insertOne(session, entity, options.getOptions());
}
} catch (MongoWriteException e) {
updateVersion(entity, versionField, oldVersion);
throw new ConcurrentModificationException(Sofia.concurrentModification(entity.getClass().getName(), idValue));
}
} else if (idValue != null) {
final UpdateResult res = find(collection.getNamespace().getCollectionName())
.filter(eq("_id", idValue),
eq(versionField.getMappedFieldName(), oldVersion))
.update(UpdateOperators.set(entity))
.execute(new UpdateOptions()
.bypassDocumentValidation(options.getBypassDocumentValidation())
.clientSession(session)
.writeConcern(options.writeConcern()));
if (res.getModifiedCount() != 1) {
throw new ConcurrentModificationException(Sofia.concurrentModification(entity.getClass().getName(), idValue));
}
updateVersion(entity, versionField, newVersion);
}
return true;
}
/**
* Adds a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to add
* @return the outcome of the operation
*/
public boolean addTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.addEachToSet(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}
/**
* Removes a list of tags to the blog post with the given title.
*
* @param title
* the title of the blog post
* @param tags
* a list of tags to remove
* @return the outcome of the operation
*/
public boolean removeTags(String title, List<String> tags) {
UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title),
Updates.pullAll(TAGS_FIELD, tags));
return result.getModifiedCount() == 1;
}