Java Code Examples for com.mongodb.client.result.UpdateResult#getModifiedCount()

The following examples show how to use com.mongodb.client.result.UpdateResult#getModifiedCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoCoordinatorRepository.java    From hmily with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: MongoCompensationServiceImpl.java    From hmily with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
Source File: DatastoreImpl.java    From morphia with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: MongoDBClient.java    From redtorch with MIT License 5 votes vote down vote up
/**
 * 更新
 * 
 * @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;
}
 
Example 5
Source File: MongoDBClient.java    From redtorch with MIT License 5 votes vote down vote up
/**
 * 通过_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;
}
 
Example 6
Source File: MongoCoordinatorRepository.java    From hmily with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 7
Source File: UpdateOneOperation.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
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()
  );
}
 
Example 8
Source File: UpdateManyOperation.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
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()
  );
}
 
Example 9
Source File: UpdateOperation.java    From mongodb-performance-test with GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: MongoRyaInstanceDetailsRepository.java    From rya with Apache License 2.0 5 votes vote down vote up
@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.");
    }
}
 
Example 12
Source File: Utils.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
static MongoClientUpdateResult toMongoClientUpdateResult(UpdateResult updateResult) {
  return updateResult.wasAcknowledged() ? new MongoClientUpdateResult(updateResult.getMatchedCount(), convertUpsertId(updateResult.getUpsertedId()), updateResult.getModifiedCount()) : null;
}
 
Example 13
Source File: DatastoreImpl.java    From morphia with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 14
Source File: TagRepository.java    From tutorials with MIT License 2 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: TagRepository.java    From tutorials with MIT License 2 votes vote down vote up
/**
 * 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;
}