Java Code Examples for com.mongodb.client.MongoCollection#updateOne()

The following examples show how to use com.mongodb.client.MongoCollection#updateOne() . 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: 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 2
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 3
Source File: ProfileActivity.java    From medical-data-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Integer doInBackground(User... params) {
    try {
        MongoClientURI mongoClientURI = new MongoClientURI(Variables.mongo_uri);
        MongoClient mongoClient = new MongoClient(mongoClientURI);
        MongoDatabase dbMongo = mongoClient.getDatabase(mongoClientURI.getDatabase());
        MongoCollection<Document> coll = dbMongo.getCollection("users");
        User local_user = params[0];
        if (!local_user.getEmail().equals(original_email)) {
            Document user = coll.find(eq("email", local_user.getEmail())).first();
            if (user != null) {
                return 1; // Repeated email
            }
        }

        Document search = new Document("_id", new ObjectId(local_user.getId()));
        Document replacement = new Document("$set", local_user.getRegisterDocument());
        // We update some fields of the documents without affecting the rest
        coll.updateOne(search, replacement);
        mongoClient.close();
        return 0; //Successfully saved
    } catch (Exception e) {
        return 2; // Error
    }
}
 
Example 4
Source File: Update.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the update
 *
 * @param options the options to apply
 * @return the results
 */
public UpdateResult execute(final UpdateOptions options) {
    Document updateOperations = toDocument();
    final Document queryObject = getQuery().toDocument();

    ClientSession session = getDatastore().findSession(options);
    MongoCollection<T> mongoCollection = options.prepare(getCollection());
    if (options.isMulti()) {
        return session == null ? mongoCollection.updateMany(queryObject, updateOperations, options)
                               : mongoCollection.updateMany(session, queryObject, updateOperations, options);

    } else {
        return session == null ? mongoCollection.updateOne(queryObject, updateOperations, options)
                               : mongoCollection.updateOne(session, queryObject, updateOperations, options);
    }
}
 
Example 5
Source File: MongoCompensableRepository.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void markTransactionRollback(TransactionXid transactionXid) {
	try {
		byte[] global = transactionXid.getGlobalTransactionId();
		String identifier = ByteUtils.byteArrayToString(global);

		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 document = new Document();
		document.append("$set", new Document("status", Status.STATUS_MARKED_ROLLBACK));

		Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, identifier);
		Bson statusFilter = Filters.eq("status", Status.STATUS_ACTIVE);

		collection.updateOne(Filters.and(globalFilter, statusFilter), document);
	} catch (RuntimeException error) {
		logger.error("Error occurred while setting the error flag.", error);
	}
}
 
Example 6
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 7
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 8
Source File: MongoRepository.java    From javers with Apache License 2.0 5 votes vote down vote up
private void persistHeadId(Commit commit) {
    MongoCollection<Document> headIdCollection = headCollection();

    Document oldHead = headIdCollection.find().first();
    MongoHeadId newHeadId = new MongoHeadId(commit.getId());

    if (oldHead == null) {
        headIdCollection.insertOne(newHeadId.toDocument());
    } else {
        headIdCollection.updateOne(objectIdFiler(oldHead), newHeadId.getUpdateCommand());
    }
}
 
Example 9
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 10
Source File: MongoConnectionWrapper.java    From mongowp with Apache License 2.0 5 votes vote down vote up
@Override
public void asyncUpdate(
    String database,
    String collection,
    BsonDocument selector,
    BsonDocument update,
    boolean upsert,
    boolean multiUpdate) throws MongoException {

  try {
    UpdateOptions updateOptions = new UpdateOptions().upsert(
        upsert
    );

    MongoCollection<org.bson.BsonDocument> mongoCollection =
        owner.getDriverClient()
            .getDatabase(database)
            .getCollection(collection, org.bson.BsonDocument.class);
    org.bson.BsonDocument translatedUpdate =
        MongoBsonTranslator.translate(update);
    if (multiUpdate) {
      mongoCollection.updateMany(translatedUpdate, translatedUpdate, updateOptions);
    } else {
      mongoCollection.updateOne(translatedUpdate, translatedUpdate, updateOptions);
    }
  } catch (com.mongodb.MongoException ex) { //a general Mongo driver exception
    if (ErrorCode.isErrorCode(ex.getCode())) {
      throw toMongoException(ex);
    } else {
      throw toRuntimeMongoException(ex);
    }
  }
}
 
Example 11
Source File: MongoCollectionSave.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase db = getMongoDatabase( _session, argStruct );

	String collection = getNamedStringParam( argStruct, "collection", null );
	if ( collection == null )
		throwException( _session, "please specify a collection" );

	cfData data = getNamedParam( argStruct, "data", null );
	if ( data == null )
		throwException( _session, "please specify data to save" );

	try {
		Document doc = getDocument( data );
		MongoCollection<Document> col = db.getCollection( collection );
		long start = System.currentTimeMillis();

		if ( doc.containsKey( "_id" ) ) {
			col.updateOne( new Document( "_id", doc.get( "_id" ) ), new Document("$set",doc) );
		} else {
			col.insertOne( doc );
		}

		_session.getDebugRecorder().execMongo( col, "save", doc, System.currentTimeMillis() - start );

		return cfBooleanData.TRUE;

	} catch ( Exception me ) {
		throwException( _session, me.getMessage() );
		return null;
	}
}
 
Example 12
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/mongodb")
public String mongoDBCase() {
    try (MongoClient mongoClient = new MongoClient(host, port)) {
        MongoDatabase db = mongoClient.getDatabase("test-database");
        // CreateCollectionOperation
        db.createCollection("testCollection");

        MongoCollection<Document> collection = db.getCollection("testCollection");
        Document document = Document.parse("{id: 1, name: \"test\"}");
        // MixedBulkWriteOperation
        collection.insertOne(document);

        // FindOperation
        FindIterable<Document> findIterable = collection.find(eq("name", "org"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.updateOne(eq("name", "org"), BsonDocument.parse("{ $set : { \"name\": \"testA\"} }"));

        // FindOperation
        findIterable = collection.find(eq("name", "testA"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.deleteOne(eq("id", "1"));

        // DropDatabaseOperation
        mongoClient.dropDatabase("test-database");
    }
    return "success";
}
 
Example 13
Source File: MongoDbDataProviderEngine.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private Object updateOne(Map<String, Object> inParams, MongoCollection<Document> collection) {
    if (!inParams.containsKey("id"))
        throw new N2oException("Id is required for operation \"updateOne\"");

    String id = (String) inParams.get("id");
    Map<String, Object> data = new HashMap<>(inParams);
    data.remove("id");

    collection.updateOne(eq("_id", new ObjectId(id)), new Document("$set", new Document(data)));
    return null;
}
 
Example 14
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 15
Source File: AddAuthorsToBooks.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
        MongoClient client = new MongoClient("localhost", 27017);
        MongoDatabase library = client.getDatabase("library");
        MongoCollection books = library.getCollection("books");
        
        try {
            Scanner scanner = new Scanner(AUTHORS_BOOKS);
            int n = 0;
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                Scanner lineScanner = new Scanner(line).useDelimiter("/");
                String author_id = lineScanner.next();
                String book_id = lineScanner.next();
                lineScanner.close();
                
//                Document doc = new Document().append("author_id", author_id);
                Document doc = new Document("author_id", author_id);
                books.updateOne(
                        eq("_id", book_id), 
                        Updates.addToSet("author", doc));
//                System.out.printf("%4d. %s, %s%n", ++n, _id, author);
            }
            scanner.close();
        } catch (IOException e) {
            System.err.println(e);
        }        
    }
 
Example 16
Source File: MongodbClientOpsDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
private static void update() {
    MongoCollection<Person> collection = Mongo.getCollection("dianping-collection", Person.class);
    //更新一条document
    collection.updateOne(eq("name", "张三"), combine(set("age", 23), set("name", "Ada Lovelace")));

    // 更新多条document
    UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
    System.out.println(updateResult.getModifiedCount());

    // 替换collection(理论上object id是不会被替换的)
    updateResult = collection.replaceOne(eq("name", "张三"), new Person("张三", 20, new Address("香柏广场", "广州", "10086")));
    System.out.println(updateResult.getModifiedCount());
}
 
Example 17
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 18
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 19
Source File: PutMongo.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String mode = context.getProperty(MODE).getValue();
    final String updateMode = context.getProperty(UPDATE_MODE).getValue();
    final WriteConcern writeConcern = getWriteConcern(context);

    try {
        final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern);
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, content, true));

        // parse
        final Object doc = (mode.equals(MODE_INSERT) || (mode.equals(MODE_UPDATE) && updateMode.equals(UPDATE_WITH_DOC.getValue())))
                ? Document.parse(new String(content, charset)) : JSON.parse(new String(content, charset));

        if (MODE_INSERT.equalsIgnoreCase(mode)) {
            collection.insertOne((Document)doc);
            logger.info("inserted {} into MongoDB", new Object[] { flowFile });
        } else {
            // update
            final boolean upsert = context.getProperty(UPSERT).asBoolean();
            final String updateKey = context.getProperty(UPDATE_QUERY_KEY).evaluateAttributeExpressions(flowFile).getValue();
            final String filterQuery = context.getProperty(UPDATE_QUERY).evaluateAttributeExpressions(flowFile).getValue();
            final Document query;

            if (!StringUtils.isBlank(updateKey)) {
                query = parseUpdateKey(updateKey, (Map)doc);
                removeUpdateKeys(updateKey, (Map)doc);
            } else {
                query = Document.parse(filterQuery);
            }

            if (updateMode.equals(UPDATE_WITH_DOC.getValue())) {
                collection.replaceOne(query, (Document)doc, new UpdateOptions().upsert(upsert));
            } else {
                BasicDBObject update = (BasicDBObject)doc;
                update.remove(updateKey);
                collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
            }
            logger.info("updated {} into MongoDB", new Object[] { flowFile });
        }

        session.getProvenanceReporter().send(flowFile, getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        logger.error("Failed to insert {} into MongoDB due to {}", new Object[] {flowFile, e}, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
 
Example 20
Source File: MongoSdkBase.java    From Mongodb-WeAdmin with Apache License 2.0 3 votes vote down vote up
/**
 * 根据条件更新单条记录
 *
 * @param table  表连接
 * @param obj
 * @return
 */
@SuppressWarnings("rawtypes")
public  boolean updateOne(MongoCollection table, String id, Object obj) {
    Bson filter = eq("_id", id);
    table.updateOne(filter, set(diyObjectIdToJson(obj)));
    return true;
}