com.mongodb.client.result.UpdateResult#getMatchedCount ( )源码实例Demo

下面列出了com.mongodb.client.result.UpdateResult#getMatchedCount ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: grain   文件: MongodbManager.java
/**
 * 修改记录
 * 
 * @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;
	}

}
 
源代码2 项目: jpa-unit   文件: RefreshOperation.java
@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);
            }
        }
    }
}
 
源代码3 项目: ByteTCC   文件: MongoCompensableLock.java
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;
	}
}
 
源代码4 项目: fiware-cygnus   文件: MongoBackendImpl.java
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);
}
 
@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);
}
 
@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);
}
 
源代码7 项目: stitch-android-sdk   文件: UpdateOneOperation.java
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()
  );
}
 
源代码8 项目: stitch-android-sdk   文件: UpdateManyOperation.java
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()
  );
}
 
源代码9 项目: ByteTCC   文件: MongoCompensableLogger.java
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();
	}
}
 
源代码10 项目: ByteTCC   文件: MongoCompensableRepository.java
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);
	}
}
 
源代码11 项目: render   文件: RenderDao.java
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());
    }
 
源代码12 项目: fiware-cygnus   文件: MongoBackendImpl.java
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
}
 
源代码13 项目: ByteTCC   文件: MongoCompensableLogger.java
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()));
	}
}
 
源代码14 项目: ByteTCC   文件: MongoCompensableLogger.java
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()));
	}
}
 
源代码15 项目: render   文件: RenderDao.java
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());
    }
}
 
源代码16 项目: vertx-mongo-client   文件: Utils.java
static MongoClientUpdateResult toMongoClientUpdateResult(UpdateResult updateResult) {
  return updateResult.wasAcknowledged() ? new MongoClientUpdateResult(updateResult.getMatchedCount(), convertUpsertId(updateResult.getUpsertedId()), updateResult.getModifiedCount()) : null;
}