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

The following examples show how to use com.mongodb.client.result.UpdateResult#getMatchedCount() . 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: MongodbManager.java    From grain with MIT License 6 votes vote down vote up
/**
 * 修改记录
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            对象
 * @return
 */
public static boolean updateById(String collectionName, MongoObj mongoObj) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
		mongoObj.setDocument(null);
		Document document = objectToDocument(mongoObj);
		UpdateResult result = collection.updateOne(filter, new Document(MongoConfig.$SET, document));
		if (result.getMatchedCount() == 1) {
			return true;
		} else {
			return false;
		}
	} catch (Exception e) {
		if (log != null) {
			log.error("修改记录失败", e);
		}
		return false;
	}

}
 
Example 2
Source File: RefreshOperation.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final MongoDatabase connection, final Document data) {
    for (final String collectionName : data.keySet()) {
        final MongoCollection<Document> collection = connection.getCollection(collectionName);

        @SuppressWarnings("unchecked")
        final List<Document> documents = data.get(collectionName, List.class);

        for (final Document doc : documents) {
            final UpdateResult result = collection.replaceOne(Filters.eq(doc.get("_id")), doc);

            if (result.getMatchedCount() == 0) {
                collection.insertOne(doc);
            }
        }
    }
}
 
Example 3
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean takeOverTransactionInMongoDB(TransactionXid transactionXid, String source, String target) {
	byte[] global = transactionXid.getGlobalTransactionId();
	String instanceId = ByteUtils.byteArrayToString(global);

	try {
		String application = CommonUtils.getApplication(this.endpoint);
		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS);

		Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId);
		Bson instIdFilter = Filters.eq("identifier", source);

		Document document = new Document("$set", new Document("identifier", target));

		UpdateResult result = collection.updateOne(Filters.and(globalFilter, instIdFilter), document);
		return result.getMatchedCount() == 1;
	} catch (RuntimeException rex) {
		logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex);
		return false;
	}
}
 
Example 4
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        double max, double min, double sum, double sum2, int numSamples, Resolution resolution) {
    // Get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // Build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // Prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution, true);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // Do the update
    BasicDBObject update = buildUpdateForUpdate(attrType, calendar, max, min, sum, sum2, numSamples);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
            + query.toString() + ", update=" + update.toString());
    collection.updateOne(query, update);
}
 
Example 5
Source File: PersonServiceWithMongo.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{personId}")
public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
    UpdateResult result = peopleCollection.replaceOne(eq("id", id), p.toDocument());
    if (result.getMatchedCount() != 1)
        personNotFound(id);
}
 
Example 6
Source File: PersonServiceWithMongo.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{personId}")
public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
    UpdateResult result = peopleCollection.replaceOne(eq("id", id), p.toDocument());
    if (result.getMatchedCount() != 1)
        personNotFound(id);
}
 
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: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void deleteParticipant(XAResourceArchive archive) {
	try {
		TransactionXid transactionXid = (TransactionXid) archive.getXid();
		byte[] global = transactionXid.getGlobalTransactionId();
		byte[] branch = transactionXid.getBranchQualifier();
		String globalKey = ByteUtils.byteArrayToString(global);
		String branchKey = ByteUtils.byteArrayToString(branch);

		String application = CommonUtils.getApplication(this.endpoint);

		String databaseName = application.replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

		Document participants = new Document();
		participants.append(String.format("participants.%s", branchKey), null);

		Document document = new Document();
		document.append("$unset", participants);

		UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, globalKey), document);
		if (result.getMatchedCount() != 1) {
			throw new IllegalStateException(
					String.format("Error occurred while deleting participant(matched= %s, modified= %s).",
							result.getMatchedCount(), result.getModifiedCount()));
		}
	} catch (RuntimeException error) {
		logger.error("Error occurred while deleting participant.", error);
		this.beanFactory.getCompensableManager().setRollbackOnlyQuietly();
	}
}
 
Example 10
Source File: MongoCompensableRepository.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void putErrorTransaction(TransactionXid transactionXid, Transaction transaction) {
	try {
		TransactionArchive archive = (TransactionArchive) transaction.getTransactionArchive();
		byte[] global = transactionXid.getGlobalTransactionId();
		String identifier = ByteUtils.byteArrayToString(global);

		int status = archive.getCompensableStatus();

		String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
		MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
		MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

		Document target = new Document();
		target.append("modified", this.endpoint);
		target.append("status", status);
		target.append("error", true);
		target.append("recovered_at", archive.getRecoveredAt() == 0 ? null : new Date(archive.getRecoveredAt()));
		target.append("recovered_times", archive.getRecoveredTimes());

		Document document = new Document();
		document.append("$set", target);
		// document.append("$inc", new BasicDBObject("modified_time", 1));

		UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, identifier), document);
		if (result.getMatchedCount() != 1) {
			throw new IllegalStateException(
					String.format("Error occurred while updating transaction(matched= %s, modified= %s).",
							result.getMatchedCount(), result.getModifiedCount()));
		}
	} catch (RuntimeException error) {
		logger.error("Error occurred while setting the error flag.", error);
	}
}
 
Example 11
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void saveStackMetaData(final StackMetaData stackMetaData) {

        LOG.debug("saveStackMetaData: entry, stackMetaData={}", stackMetaData);

        MongoUtil.validateRequiredParameter("stackMetaData", stackMetaData);

        final StackId stackId = stackMetaData.getStackId();
        final MongoCollection<Document> stackMetaDataCollection = getStackMetaDataCollection();

        final Document query = getStackIdQuery(stackId);
        final Document stackMetaDataObject = Document.parse(stackMetaData.toJson());
        final UpdateResult result = stackMetaDataCollection.replaceOne(query,
                                                                       stackMetaDataObject,
                                                                       MongoUtil.UPSERT_OPTION);

        final String action;
        if (result.getMatchedCount() > 0) {
            action = "update";
        } else {
            action = "insert";
            ensureCoreTransformIndex(getTransformCollection(stackId));
            ensureCoreTileIndexes(getTileCollection(stackId));
        }

        LOG.debug("saveStackMetaData: {}.{}({})",
                  stackMetaDataCollection.getNamespace().getFullName(), action, query.toJson());
    }
 
Example 12
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        HashMap<String, Integer> counts, Resolution resolution) {
    // Get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // Build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // Prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution, false);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // Do the update
    for (String key : counts.keySet()) {
        int count = counts.get(key);
        BasicDBObject update = buildUpdateForUpdate(attrType, resolution, calendar, key, count);
        LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", update=" + update.toString());
        collection.updateOne(query, update);
    } // for
}
 
Example 13
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void upsertParticipant(XAResourceArchive archive) {
	TransactionXid transactionXid = (TransactionXid) archive.getXid();
	byte[] global = transactionXid.getGlobalTransactionId();
	byte[] branch = transactionXid.getBranchQualifier();
	String globalKey = ByteUtils.byteArrayToString(global);
	String branchKey = ByteUtils.byteArrayToString(branch);
	XAResourceDescriptor descriptor = archive.getDescriptor();
	String descriptorType = descriptor.getClass().getName();
	String descriptorKey = descriptor.getIdentifier();

	int branchVote = archive.getVote();
	boolean readonly = archive.isReadonly();
	boolean committed = archive.isCommitted();
	boolean rolledback = archive.isRolledback();
	boolean completed = archive.isCompleted();
	boolean heuristic = archive.isHeuristic();

	String application = CommonUtils.getApplication(this.endpoint);

	Document participant = new Document();
	participant.append(CONSTANTS_FD_GLOBAL, globalKey);
	participant.append(CONSTANTS_FD_BRANCH, branchKey);

	participant.append("type", descriptorType);
	participant.append("resource", descriptorKey);

	participant.append("vote", branchVote);
	participant.append("committed", committed);
	participant.append("rolledback", rolledback);
	participant.append("readonly", readonly);
	participant.append("completed", completed);
	participant.append("heuristic", heuristic);

	String databaseName = application.replaceAll("\\W", "_");
	MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

	Document participants = new Document();
	participants.append(String.format("participants.%s", branchKey), participant);

	Document document = new Document();
	document.append("$set", participants);

	UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, globalKey), document);
	if (result.getMatchedCount() != 1) {
		throw new IllegalStateException(
				String.format("Error occurred while creating/updating participant(matched= %s, modified= %s).",
						result.getMatchedCount(), result.getModifiedCount()));
	}
}
 
Example 14
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void upsertCompensable(CompensableArchive archive) throws IOException {
	TransactionXid xid = (TransactionXid) archive.getIdentifier();
	byte[] global = xid.getGlobalTransactionId();
	byte[] branch = xid.getBranchQualifier();
	String globalKey = ByteUtils.byteArrayToString(global);
	String branchKey = ByteUtils.byteArrayToString(branch);
	CompensableInvocation invocation = archive.getCompensable();
	String beanId = (String) invocation.getIdentifier();

	Method method = invocation.getMethod();
	Object[] args = invocation.getArgs();

	String methodDesc = SerializeUtils.serializeMethod(invocation.getMethod());
	byte[] argsByteArray = SerializeUtils.serializeObject(args);
	String argsValue = ByteUtils.byteArrayToString(argsByteArray);

	String application = CommonUtils.getApplication(this.endpoint);

	Document compensable = new Document();
	compensable.append(CONSTANTS_FD_GLOBAL, globalKey);
	compensable.append(CONSTANTS_FD_BRANCH, branchKey);

	compensable.append("transaction_key", archive.getTransactionResourceKey());
	compensable.append("compensable_key", archive.getCompensableResourceKey());

	Xid transactionXid = archive.getTransactionXid();
	Xid compensableXid = archive.getCompensableXid();

	compensable.append("transaction_xid", String.valueOf(transactionXid));
	compensable.append("compensable_xid", String.valueOf(compensableXid));

	compensable.append("coordinator", archive.isCoordinator());
	compensable.append("tried", archive.isTried());
	compensable.append("confirmed", archive.isConfirmed());
	compensable.append("cancelled", archive.isCancelled());

	compensable.append("serviceId", beanId);
	compensable.append("simplified", invocation.isSimplified());
	compensable.append("confirmable_key", invocation.getConfirmableKey());
	compensable.append("cancellable_key", invocation.getCancellableKey());
	compensable.append("args", argsValue);
	compensable.append("interface", method.getDeclaringClass().getName());
	compensable.append("method", methodDesc);

	String databaseName = application.replaceAll("\\W", "_");
	MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

	Document compensables = new Document();
	compensables.append(String.format("compensables.%s", branchKey), compensable);

	Document document = new Document();
	document.append("$set", compensables);

	UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, globalKey), document);
	if (result.getMatchedCount() != 1) {
		throw new IllegalStateException(
				String.format("Error occurred while creating/updating compensable(matched= %s, modified= %s).",
						result.getMatchedCount(), result.getModifiedCount()));
	}
}
 
Example 15
Source File: RenderDao.java    From render with GNU General Public License v2.0 4 votes vote down vote up
private void saveResolvedTransforms(final StackId stackId,
                                    final Collection<TransformSpec> transformSpecs) {

    final MongoCollection<Document> transformCollection = getTransformCollection(stackId);

    int updateCount = 0;
    int insertCount = 0;
    UpdateResult result;
    for (final TransformSpec transformSpec : transformSpecs) {
        final Document query = new Document("id", transformSpec.getId());
        final Document transformSpecObject = Document.parse(transformSpec.toJson());
        try {
            result = transformCollection.replaceOne(query,
                                                    transformSpecObject,
                                                    MongoUtil.UPSERT_OPTION);
            if (result.getMatchedCount() > 0) {
                updateCount++;
            } else {
                insertCount++;
            }
        } catch (final MongoException e) {
            LOG.warn("possible duplicate key exception thrown for upsert, retrying operation ...", e);

            result = transformCollection.replaceOne(query,
                                                    transformSpecObject,
                                                    MongoUtil.UPSERT_OPTION);
            if (result.getMatchedCount() > 0) {
                updateCount++;
            } else {
                insertCount++;
            }
        }

    }

    // TODO: re-derive bounding boxes for all tiles (outside this collection) that reference modified transforms

    if (LOG.isDebugEnabled()) {
        LOG.debug("saveResolvedTransforms: inserted {} and updated {} documents in {})",
                  insertCount, updateCount, transformCollection.getNamespace().getFullName());
    }
}
 
Example 16
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;
}