use of com.mongodb.client.model.UpdateOptions in project nifi by apache.
the class PutMongo method onTrigger.
@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);
final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern);
try {
// 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();
}
}
use of com.mongodb.client.model.UpdateOptions in project spring-data-mongodb by spring-projects.
the class ReactiveMongoTemplate method doUpdate.
protected Mono<UpdateResult> doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class<?> entityClass, final boolean upsert, final boolean multi) {
MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
Flux<UpdateResult> result = execute(collectionName, collection -> {
increaseVersionForUpdateIfNecessary(entity, update);
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
}
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
if (!UpdateMapper.isUpdateObject(updateObj)) {
return collectionToUse.replaceOne(queryObj, updateObj, updateOptions);
}
if (multi) {
return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
}
return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
}).doOnNext(updateResult -> {
if (entity != null && entity.hasVersionProperty() && !multi) {
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
if (dbObjectContainsVersionProperty(queryObj, entity))
throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toString() + " to collection " + collectionName);
}
}
});
return result.next();
}
use of com.mongodb.client.model.UpdateOptions in project LuckPerms by lucko.
the class MongoDao method savePlayerData.
@Override
public PlayerSaveResult savePlayerData(UUID uuid, String username) {
username = username.toLowerCase();
MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid");
// find any existing mapping
String oldUsername = getPlayerName(uuid);
// do the insert
if (!username.equalsIgnoreCase(oldUsername)) {
c.replaceOne(new Document("_id", uuid), new Document("_id", uuid).append("name", username), new UpdateOptions().upsert(true));
}
PlayerSaveResult result = PlayerSaveResult.determineBaseResult(username, oldUsername);
Set<UUID> conflicting = new HashSet<>();
try (MongoCursor<Document> cursor = c.find(new Document("name", username)).iterator()) {
if (cursor.hasNext()) {
conflicting.add(cursor.next().get("_id", UUID.class));
}
}
conflicting.remove(uuid);
if (!conflicting.isEmpty()) {
// remove the mappings for conflicting uuids
c.deleteMany(Filters.and(conflicting.stream().map(u -> Filters.eq("_id", u)).collect(Collectors.toList())));
result = result.withOtherUuidsPresent(conflicting);
}
return result;
}
use of com.mongodb.client.model.UpdateOptions in project duangframework by tcrct.
the class MongoBaseDao method update.
private boolean update(String id, Document document) throws Exception {
if (!ObjectId.isValid(id)) {
throw new MongodbException("id is not ObjectId!");
}
Document query = new Document(IdEntity.ID_FIELD, new ObjectId(id));
// 查询记录不存在时,不新增记录
UpdateOptions options = new UpdateOptions();
options.upsert(false);
document.remove(IdEntity.ENTITY_ID_FIELD);
BasicDBObject updateDbo = new BasicDBObject(Operator.SET, document);
return collection.updateOne(query, updateDbo, options).isModifiedCountAvailable();
}
use of com.mongodb.client.model.UpdateOptions in project webprotege by protegeproject.
the class UserRecordRepository method save.
public void save(UserRecord userRecord) {
Document document = converter.toDocument(userRecord);
collection.replaceOne(byUserId(userRecord.getUserId()), document, new UpdateOptions().upsert(true));
}
Aggregations