protected final FluentFuture<Integer> doUpdate( final Constraints.ConstraintHost criteria, final Constraints.Constraint update, final UpdateOptions options) { checkNotNull(criteria, "criteria"); checkNotNull(update, "update"); checkNotNull(options, "options"); return submit(new Callable<UpdateResult>() { @Override public UpdateResult call() { return collection() .updateMany( convertToBson(criteria), convertToBson(update), options); } }).lazyTransform(new Function<UpdateResult, Integer>() { @Override public Integer apply(UpdateResult input) { return (int) input.getModifiedCount(); } }); }
protected final FluentFuture<Integer> doUpsert( final Constraints.ConstraintHost criteria, final T document) { checkNotNull(criteria, "criteria"); checkNotNull(document, "document"); return submit(new Callable<Integer>() { @Override public Integer call() { collection().replaceOne(convertToBson(criteria), document, new UpdateOptions().upsert(true)); // upsert will always return 1: // if document doesn't exists, it will be inserted (modCount == 1) // if document exists, it will be updated (modCount == 1) return 1; } }); }
@Override public ActivityCategory update(ActivityCategory activityCategory) throws DataNotFoundException { BasicDBObject query = new BasicDBObject(); query.put("objectType", "ActivityCategory"); query.put("name", activityCategory.getName()); UpdateResult updateResult = collection.updateOne(query, new Document("$set", new Document("label",activityCategory.getLabel())), new UpdateOptions().upsert(false)); if (updateResult.getMatchedCount() == 0){ throw new DataNotFoundException( new Throwable("ActivityCategory {" + activityCategory.getName() + "} not found.")); } return activityCategory; }
@Override public void setNewDefault(String name) throws DataNotFoundException { BasicDBObject query = new BasicDBObject(); query.put("objectType", "ActivityCategory"); query.put("isDefault", true); UpdateResult undefaultResult = collection.updateOne(query, new Document("$set", new Document("isDefault", false)), new UpdateOptions().upsert(false)); if (undefaultResult.getMatchedCount() > 1){ throw new DataNotFoundException( new Throwable("Default category error. More than one default found")); } BasicDBObject otherQuery = new BasicDBObject(); otherQuery.put("objectType", "ActivityCategory"); otherQuery.put("name", name); UpdateResult defaultSetResult = collection.updateOne(otherQuery, new Document("$set", new Document("isDefault", true)), new UpdateOptions().upsert(false)); if (defaultSetResult.getMatchedCount() == 0){ throw new DataNotFoundException( new Throwable("ActivityCategory {" + name + "} not found.")); } }
@Override public Tube updateTubeCollectionData(long rn,Tube tube) throws DataNotFoundException { Document parsedCollectionData = Document.parse(TubeCollectionData.serialize(tube.getTubeCollectionData())); UpdateResult updateLabData = collection.updateOne(and(eq("recruitmentNumber", rn), eq("tubes.code",tube.getCode())), set("tubes.$.tubeCollectionData", parsedCollectionData), new UpdateOptions().upsert(false)); if (updateLabData.getMatchedCount() == 0) { throw new DataNotFoundException(new Throwable("Laboratory of Participant recruitment number: " + rn + " does not exists.")); } return tube; }
@Override public UpdateResult updateMany(Bson filter, Bson arg1, UpdateOptions arg2) { int writeSize = 0; OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); keyValuePairs.add("update"); keyValuePairs.add(arg1.toString()); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateMany : " + MongoUtilities.filterParameters(filter); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } UpdateResult retVal = collection.updateMany(filter, arg1, arg2); insertUpdateResultProperties(metric, retVal); stopMetric(metric, writeSize); return retVal; }
@Override public UpdateResult updateOne(Bson filter, Bson arg1, UpdateOptions arg2) { int writeSize = 0; OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); keyValuePairs.add("update"); keyValuePairs.add(arg1.toString()); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : updateOne : " + MongoUtilities.filterParameters(filter); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } UpdateResult retVal = collection.updateOne(filter, arg1, arg2); insertUpdateResultProperties(metric, retVal); stopMetric(metric, writeSize); return retVal; }
@Override public String storeConversationMemorySnapshot(ConversationMemorySnapshot snapshot) throws IResourceStore.ResourceStoreException { try { String json = documentBuilder.toString(snapshot); Document document = Document.parse(json); document.remove("id"); if (snapshot.getId() != null) { document.put("_id", new ObjectId(snapshot.getId())); conversationCollection.updateOne(new Document("_id", new ObjectId(snapshot.getId())), new Document("$set", document), new UpdateOptions().upsert(true)); } else { conversationCollection.insertOne(document); } return document.get("_id").toString(); } catch (IOException e) { throw new IResourceStore.ResourceStoreException(e.getLocalizedMessage(), e); } }
private Function<Exchange, Object> createDoSave() { return exchange1 -> { try { MongoCollection<BasicDBObject> dbCol = calculateCollection(exchange1); BasicDBObject saveObj = exchange1.getIn().getMandatoryBody(BasicDBObject.class); UpdateOptions options = new UpdateOptions().upsert(true); BasicDBObject queryObject = new BasicDBObject("_id", saveObj.get("_id")); UpdateResult result = dbCol.replaceOne(queryObject, saveObj, options); exchange1.getIn().setHeader(MongoDbConstants.OID, saveObj.get("_id")); return result; } catch (InvalidPayloadException e) { throw new CamelMongoDbException("Body incorrect type for save", e); } }; }
@Override public void replace(T entity) { StopWatch watch = new StopWatch(); Object id = null; validator.validate(entity); try { id = mongo.codecs.id(entity); if (id == null) throw Exceptions.error("entity must have id, entityClass={}", entityClass.getCanonicalName()); collection().replaceOne(Filters.eq("_id", id), entity, new UpdateOptions().upsert(true)); } finally { long elapsedTime = watch.elapsedTime(); ActionLogContext.track("mongoDB", elapsedTime, 0, 1); logger.debug("replace, collection={}, id={}, elapsedTime={}", collectionName, id, elapsedTime); checkSlowOperation(elapsedTime); } }
/** * Need to page the session out to Mongo * @param session */ public void onRequestEnd(cfSession Session) { cfSessionData sessData = getSessionData( Session ); if ( sessData == null ) return; try{ Document keys = new Document("_id", appName + sessData.getStorageID() ); Document vals = new Document("et", new Date(System.currentTimeMillis() + sessData.getTimeOut() ) ); // Serialize the object ByteArrayOutputStreamRaw bos = new ByteArrayOutputStreamRaw( 32000 ); FileUtil.saveClass(bos, sessData, true); byte[] buf = bos.toByteArray(); // Has it really changed; we only update the last used date if it has if ( !MD5.getDigest(buf).equals( sessData.getMD5() ) ) vals.append("d", buf); col.updateOne( keys, new Document("$set", vals), new UpdateOptions().upsert(true) ); }catch(Exception e){ cfEngine.log( appName + "MongoDBException: " + e ); } }
/** * Un-assigns a key/value property from the element. The object value of the * removed property is returned. * * @param key * the key of the property to remove from the element * @return the object value associated with that key prior to removal. Should be * instance of BsonValue */ @Override public <T> T removeProperty(final String key) { try { BsonValue value = getProperty(key); BsonDocument filter = new BsonDocument(); filter.put(Tokens.ID, new BsonString(this.id)); BsonDocument update = new BsonDocument(); update.put("$unset", new BsonDocument(key, new BsonNull())); if (this instanceof ChronoVertex) { graph.getVertexCollection().updateOne(filter, update, new UpdateOptions().upsert(true)); return (T) value; } else { graph.getEdgeCollection().updateOne(filter, update, new UpdateOptions().upsert(true)); return (T) value; } } catch (MongoWriteException e) { throw e; } }
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); }
public static void storeBlock(MongoBlock mongoBlock) { // System.out.println("Store: " + mongoBlock.getBlockNumber()); MongoCollection<Document> c = mongoBlock.mongoFile.mongoDirectory.getBlocksCollection(); Document query = new Document(); query.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber); query.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber); Document object = new Document(); object.put(MongoDirectory.FILE_NUMBER, mongoBlock.mongoFile.fileNumber); object.put(MongoDirectory.BLOCK_NUMBER, mongoBlock.blockNumber); object.put(MongoDirectory.BYTES, new Binary(mongoBlock.bytes)); c.replaceOne(query, object, new UpdateOptions().upsert(true)); }
private void storeIndexSettings() { indexLock.writeLock().lock(); try { MongoDatabase db = mongo.getDatabase(mongoConfig.getDatabaseName()); MongoCollection<Document> dbCollection = db.getCollection(indexConfig.getIndexName() + CONFIG_SUFFIX); Document settings = IndexConfigUtil.toDocument(indexConfig); settings.put(MongoConstants.StandardFields._ID, SETTINGS_ID); Document query = new Document(); query.put(MongoConstants.StandardFields._ID, SETTINGS_ID); dbCollection.replaceOne(query, settings, new UpdateOptions().upsert(true)); } finally { indexLock.writeLock().unlock(); } }
@Override public void storeSourceDocument(String uniqueId, long timeStamp, Document document, List<Metadata> metaDataList) throws Exception { MongoDatabase db = mongoClient.getDatabase(database); MongoCollection<Document> coll = db.getCollection(rawCollectionName); Document mongoDocument = new Document(); mongoDocument.putAll(document); if (!metaDataList.isEmpty()) { Document metadataMongoDoc = new Document(); for (Metadata meta : metaDataList) { metadataMongoDoc.put(meta.getKey(), meta.getValue()); } mongoDocument.put(METADATA, metadataMongoDoc); } mongoDocument.put(TIMESTAMP, timeStamp); mongoDocument.put(MongoConstants.StandardFields._ID, uniqueId); Document query = new Document(MongoConstants.StandardFields._ID, uniqueId); coll.replaceOne(query, mongoDocument, new UpdateOptions().upsert(true)); }
@Override public void save(final Session session) { syncTtl(); String id = session.id(); Bson filter = Filters.eq("_id", id); Document doc = new Document() .append("_id", id) .append("_accessedAt", new Date(session.accessedAt())) .append("_createdAt", new Date(session.createdAt())) .append("_savedAt", new Date(session.savedAt())); // dump attributes Map<String, String> attributes = session.attributes(); attributes.forEach((k, v) -> doc.append(encode(k), v)); sessions.updateOne(filter, new Document("$set", doc), new UpdateOptions().upsert(true)); }
/** * stores the given EntityInvocationHandler represented Entity in the given Collection * * @param handler EntityInvocationHandler (Entity) to save * @param coll MongoCollection to save entity into */ @SuppressWarnings( "unchecked" ) static <T extends Entity> void save( EntityInvocationHandler handler, MongoCollection<T> coll ) { for ( ParameterProperty cpp : handler.properties.getValidationProperties() ) { cpp.validate( handler.data.get( cpp.getMongoName() ) ); } BsonDocumentWrapper wrapper = new BsonDocumentWrapper<>( handler.proxy, (org.bson.codecs.Encoder<Entity>) coll.getCodecRegistry().get( handler.properties.getEntityClass() ) ); UpdateResult res = coll.updateOne( new BsonDocument( "_id", BsonDocumentWrapper.asBsonDocument( EntityCodec._obtainId( handler.proxy ), idRegistry ) ), new BsonDocument( "$set", wrapper ), new UpdateOptions() ); if ( res.getMatchedCount() == 0 ) { // TODO this seems too nasty, there must be a better way.for now live with it coll.insertOne( (T) handler.proxy ); } handler.persist(); }
public void saveRegionData(LoadedRegion loadedRegion) { MongoCollection<Document> collection = getDatabase().getCollection("chunks"); Document regionDocument = new Document("_id", loadedRegion.getUniqueId().toString()) .append("owner", loadedRegion.getOwner().toString()) .append("world", loadedRegion.getWorld().getUniqueId().toString()) .append("type", loadedRegion.getType().toString()) .append("fromX", loadedRegion.getRegion().getFrom().getX()) .append("fromZ", loadedRegion.getRegion().getFrom().getZ()) .append("toX", loadedRegion.getRegion().getTo().getX()) .append("toZ", loadedRegion.getRegion().getTo().getZ()) .append("created", loadedRegion.getEpoch()); collection.replaceOne( Filters.eq("_id", loadedRegion.getUniqueId().toString()), regionDocument, (new UpdateOptions()).upsert(true) ); }
public void saveUserData(UserData userData) { MongoCollection<Document> collection = getDatabase().getCollection("users"); Document userDocument = new Document("_id", userData.getUniqueId()) .append("seen", userData.getLastSeen()) .append("joined", userData.getUserJoined()); collection.replaceOne( Filters.eq("_id", userData.getUniqueId().toString()), userDocument, (new UpdateOptions()).upsert(true) ); }
public void Save(Document doc) { if (!doc.containsKey("_id")) { Create(doc); return; } Document find = new Document("_id", doc.get("_id")); UpdateOptions uo = new UpdateOptions(); uo.upsert(true); ops.add(new ReplaceOneModel<Document>(find, doc, uo)); FlushOpsIfFull(); }
public static void saveFailureStatusProcesssed(MongoDatabase mongoDatabase, long id, boolean processed) { MongoCollection<Document> failureCollection = mongoDatabase.getCollection("failures"); failureCollection.replaceOne( Filters.eq("tweet_id", id), new Document().append("tweet_id", id).append("processed", processed), new UpdateOptions().upsert(true)); }
/** * Inserts new resource to DB, or else updates existing resource description if existing ID was used * * @param resource resource to be upserted */ public synchronized void insert(Resource resource) { this.thisCollection.replaceOne( eq("_id", resource.getId()), resourceToDocument(resource), new UpdateOptions().upsert(true)); }
/** * Inserts new resources to DB, or else updates existing ones descriptions if existing ID`s was used * * @param resource resources to be upserted */ public synchronized void insert(Set<Resource> resource) { List<ReplaceOneModel<Document>> upserts = resource.stream() .map( res -> new ReplaceOneModel<Document>( eq("_id", res.getId()), resourceToDocument(res), new UpdateOptions().upsert(true) ) ).collect(Collectors.toList()); this.thisCollection.bulkWrite(upserts); }
@Override public void save(Migration migration) { Document d = new Document("version", migration.getVersion()) .append("description", migration.getDescription()) .append("author", migration.getAuthor()) .append("started", Optional.ofNullable(migration.getStarted()).map(DateTime::toDate).orElse(null)) .append("finished", Optional.ofNullable(migration.getFinished()).map(DateTime::toDate).orElse(null)) .append("status", migration.getStatus().name()) .append("failureMessage", migration.getFailureMessage()); collection.replaceOne(eq("version", migration.getVersion()), d, new UpdateOptions().upsert(true)); }
@Override public void open(Configuration config) { mongoClient = MongoManager.getInstance().getClient(); uo = new UpdateOptions(); uo.upsert(true); try { super.open(config); } catch (Exception e) { e.printStackTrace(); } }
/** * @param dbName 库名 * @param collectionName 集合名 * @param json1 条件 * @param json2 保存doc * @return upsert结果信息 */ public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) { JSONObject resp = new JSONObject(); try { MongoDatabase db = mongoClient.getDatabase(dbName); MongoCollection coll = db.getCollection(collectionName); JSONObject saveJson = new JSONObject(); saveJson.put("$set", json2); Document doc1 = Document.parse(json1.toString()); Document doc2 = Document.parse(saveJson.toString()); UpdateOptions up = new UpdateOptions(); up.upsert(true); UpdateResult ur = coll.updateOne(doc1, doc2, up); if (ur.isModifiedCountAvailable()) { if (json1.containsKey(ID)) { resp.put("Data", json1.get(ID)); } else { resp.put("Data", json1); } } } catch (MongoTimeoutException e1) { e1.printStackTrace(); resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage()); return resp; } catch (Exception e) { e.printStackTrace(); resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage()); } return resp; }
/** * 新增或者更新 * * @param collectionName 集合名 * @param query 查询条件 * @param descData 目标数据 * @return */ public boolean upsert(String collectionName, MongodbQuery query, Map<String, Object> descData) { MongoCollection collection = sMongoDatabase.getCollection(collectionName); UpdateOptions options = new UpdateOptions(); options.upsert(true); BasicDBObject updateSetValue = new BasicDBObject("$set", descData); UpdateResult updateResult = collection.updateMany(query.getQuery(), updateSetValue, options); return updateResult.getUpsertedId() != null || (updateResult.getMatchedCount() > 0 && updateResult.getModifiedCount() > 0); }
@OnScheduled public void onScheduled(final ProcessContext context) { batchSize = context.getProperty(MongoProps.BATCH_SIZE).asInteger(); updateOperator = context.getProperty(MongoProps.UPDATE_OPERATOR).getValue(); updateQueryKeys = getSetFromCsvList(context.getProperty(MongoProps.UPDATE_QUERY_KEYS).getValue()); updateKeysProp = context.getProperty(MongoProps.UPDATE_KEYS); boolean upsert = context.getProperty(MongoProps.UPSERT).asBoolean(); updateOptions = new UpdateOptions().upsert(upsert); createMongoConnection(context); ensureIndexes(context, collection); }
@Override public SurveyActivity update(SurveyActivity surveyActivity) throws DataNotFoundException { Document parsed = Document.parse(SurveyActivity.serialize(surveyActivity)); parsed.remove("_id"); UpdateResult updateOne = collection.updateOne(eq("_id", surveyActivity.getActivityID()), new Document("$set", parsed), new UpdateOptions().upsert(false)); if (updateOne.getMatchedCount() == 0) { throw new DataNotFoundException( new Throwable("OID {" + surveyActivity.getActivityID().toString() + "} not found.")); } return surveyActivity; }
@Override public void updateCategory(ActivityCategory activityCategory){ Document query = new Document(); query.put("category.name", activityCategory.getName()); UpdateResult updateResult = collection.updateOne(query, new Document("$set", new Document("category.label", activityCategory.getLabel())), new UpdateOptions().upsert(false)); }
@Override public void disable(String name) throws DataNotFoundException { BasicDBObject query = new BasicDBObject(); query.put("objectType", "ActivityCategory"); query.put("name", name); UpdateResult updateResult = collection.updateOne(query, new Document("$set", new Document("disabled", true)), new UpdateOptions().upsert(false)); if (updateResult.getMatchedCount() == 0) { throw new DataNotFoundException( new Throwable("ActivityCategory {" + name + "} not found.")); } }
@Override public ExamLot update(ExamLot examLot) throws DataNotFoundException { Document parsed = Document.parse(ExamLot.serialize(examLot)); parsed.remove("_id"); UpdateResult updateLotData = collection.updateOne(eq("code", examLot.getCode()), new Document("$set", parsed), new UpdateOptions().upsert(false)); if (updateLotData.getMatchedCount() == 0) { throw new DataNotFoundException(new Throwable("Exam Lot not found")); } return examLot; }
@Override public TransportationLot update(TransportationLot transportationLot) throws DataNotFoundException { Document parsed = Document.parse(TransportationLot.serialize(transportationLot)); parsed.remove("_id"); UpdateResult updateLotData = collection.updateOne(eq("code", transportationLot.getCode()), new Document("$set", parsed), new UpdateOptions().upsert(false)); if (updateLotData.getMatchedCount() == 0) { throw new DataNotFoundException( new Throwable("Transportation Lot not found")); } return transportationLot; }
@Override public ParticipantLaboratory updateLaboratoryData(ParticipantLaboratory labParticipant) throws DataNotFoundException { Document parsed = Document.parse(ParticipantLaboratory.serialize(labParticipant)); parsed.remove("_id"); UpdateResult updateLabData = collection.updateOne(eq("recruitmentNumber", labParticipant.getRecruitmentNumber()), new Document("$set", parsed), new UpdateOptions().upsert(false)); if (updateLabData.getMatchedCount() == 0) { throw new DataNotFoundException(new Throwable("Laboratory of Participant recruitment number: " + labParticipant.getRecruitmentNumber() + " does not exists.")); } return labParticipant; }
@Override public void update(LaboratoryConfiguration configuration) throws Exception { Document parsed = Document.parse(LaboratoryConfiguration.serialize(configuration)); parsed.remove("_id"); UpdateResult updatedData = collection.updateOne(eq("_id", configuration.getId()), new Document("$set", parsed), new UpdateOptions().upsert(false)); if (updatedData.getModifiedCount() == 0) { throw new Exception("Update was not executed."); } }
@Override public UpdateOptions toUpdateOptions() { final UpdateOptions options = new UpdateOptions(); options.bypassDocumentValidation(!validateDocuments); options.upsert(upsert); return options; }
@Override public void saveUser(User user) { user.getIoLock().lock(); try { MongoCollection<Document> c = this.database.getCollection(this.prefix + "users"); if (!this.plugin.getUserManager().shouldSave(user)) { c.deleteOne(new Document("_id", user.getUuid())); } else { c.replaceOne(new Document("_id", user.getUuid()), userToDoc(user), new UpdateOptions().upsert(true)); } } finally { user.getIoLock().unlock(); } }