protected final FluentFuture<Optional<T>> doReplace( final Constraints.ConstraintHost criteria, final T document, final FindOneAndReplaceOptions options) { checkNotNull(criteria, "criteria"); checkNotNull(document, "document"); checkNotNull(options, "options"); return submit(new Callable<Optional<T>>() { @Override public Optional<T> call() throws Exception { @Nullable T result = collection().findOneAndReplace( convertToBson(criteria), // query document, options); return Optional.fromNullable(result); } }); }
@Override public Dataset write(Dataset dataset) { // we populate this on first write and retain it thereafter if (isBlank(dataset.getId())) { dataset.setId(ObjectId.get().toString()); } Observable<Document> observable = getCollection() .findOneAndReplace( Filters.eq("id", dataset.getId()), documentTransformer.transform(dataset), new FindOneAndReplaceOptions().upsert(true).returnDocument(ReturnDocument.AFTER)); return documentTransformer.transform(Dataset.class, observable.toBlocking().single()); }
@Override public TDocument findOneAndReplace(Bson filter, TDocument arg1, FindOneAndReplaceOptions arg2) { OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : findOneAndReplace " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName, keyValuePairs); addWriteKeyValuePairs(keyValuePairs); if (MongoLogger.isRequestSizeMeasured()) { metric.setProperty(CommonMetricProperties.REQUEST_SIZE_BYTES, Integer.toString(measureDocumentSize(arg1))); } addWriteConcern(metric); addReadConcernAndPreference(metric); } TDocument retVal = collection.findOneAndReplace(filter, arg1, arg2); stopMetric(metric, measureDocumentSizeIfResultSizeEnabled(retVal)); return retVal; }
@Test public void findOneAndReplace() { insertOneWithBulk(); Document replace = Document.parse( "{\"car_id\":\"c7a\",\"name\":\"DELETEME\",\"color\":\"Redaa\",\"cno\":\"H116aa\",\"mfdcountry\":\"India\",\"speed\":53,\"price\":4.5}"); Assert.assertNotNull(coll.findOneAndReplace(Filters.eq("name", "DELETEME"), replace)); insertOneWithBulk(); Assert.assertNotNull( coll.findOneAndReplace(Filters.eq("name", "DELETEME"), replace, new FindOneAndReplaceOptions())); coll.deleteMany(Filters.eq("name", "DELETEME")); }
/** * Updates the document if the document's ETAG is matching the given etag (conditional put). * <p> * Using this method requires that the document contains an "etag" field that is updated if * the document is changed. * </p> * * @param value the new value * @param eTag the etag used for conditional update * @param maxTime max time for the update * @param timeUnit the time unit for the maxTime value * @return {@link UpdateIfMatchResult} */ public UpdateIfMatchResult updateIfMatch(final V value, final String eTag, final long maxTime, final TimeUnit timeUnit) { final K key = keyOf(value); if (key != null) { final Bson query = and(eq(AbstractMongoRepository.ID, key), eq(ETAG, eTag)); final Document updatedETaggable = collectionWithWriteTimeout(maxTime, timeUnit).findOneAndReplace(query, encode(value), new FindOneAndReplaceOptions().returnDocument(AFTER)); if (isNull(updatedETaggable)) { final boolean documentExists = collection() .count(eq(AbstractMongoRepository.ID, key), new CountOptions().maxTime(maxTime, timeUnit)) != 0; if (documentExists) { return CONCURRENTLY_MODIFIED; } return NOT_FOUND; } return OK; } else { throw new IllegalArgumentException("Key must not be null"); } }
/** * set timestamp properties (replace) for the given timestamp * * @param timestamp * @param timestampProperties */ public void setTimestampProperties(final Long timestamp, BsonDocument timestampProperties) { if (timestampProperties == null) timestampProperties = new BsonDocument(); if (this instanceof ChronoVertex) { graph.getVertexEvents().findOneAndReplace( new BsonDocument(Tokens.VERTEX, new BsonString(this.id)).append(Tokens.TIMESTAMP, new BsonDateTime(timestamp)), Converter.makeTimestampVertexEventDocumentWithoutID(timestampProperties, this.id, timestamp), new FindOneAndReplaceOptions().upsert(true)); } else { ChronoEdge e = (ChronoEdge) this; graph.getEdgeEvents().findOneAndReplace( new BsonDocument(Tokens.OUT_VERTEX, new BsonString(e.getOutVertex().toString())) .append(Tokens.LABEL, new BsonString(e.getLabel())) .append(Tokens.TIMESTAMP, new BsonDateTime(timestamp)) .append(Tokens.IN_VERTEX, new BsonString(e.getInVertex().toString())), Converter.makeTimestampEdgeEventDocumentWithoutID(timestampProperties, this.id, timestamp), new FindOneAndReplaceOptions().upsert(true)); } }
@Override public io.vertx.ext.mongo.MongoClient findOneAndReplaceWithOptions(String collection, JsonObject query, JsonObject replace, FindOptions findOptions, UpdateOptions updateOptions, Handler<AsyncResult<JsonObject>> resultHandler) { requireNonNull(collection, "collection cannot be null"); requireNonNull(query, "query cannot be null"); requireNonNull(findOptions, "find options cannot be null"); requireNonNull(updateOptions, "update options cannot be null"); requireNonNull(resultHandler, "resultHandler cannot be null"); JsonObject encodedQuery = encodeKeyWhenUseObjectId(query); Bson bquery = wrap(encodedQuery); FindOneAndReplaceOptions foarOptions = new FindOneAndReplaceOptions(); foarOptions.sort(wrap(findOptions.getSort())); foarOptions.projection(wrap(findOptions.getFields())); foarOptions.upsert(updateOptions.isUpsert()); foarOptions.returnDocument(updateOptions.isReturningNewDocument() ? ReturnDocument.AFTER : ReturnDocument.BEFORE); MongoCollection<JsonObject> coll = getCollection(collection); coll.findOneAndReplace(bquery, replace, foarOptions, wrapCallback(resultHandler)); return this; }
protected Replacer( Repository<T> repository, T document, Constraints.ConstraintHost criteria, Constraints.Constraint ordering) { super(repository); this.document = checkNotNull(document, "document"); this.criteria = checkNotNull(criteria, "criteria"); this.ordering = checkNotNull(ordering, "ordering"); this.options = new FindOneAndReplaceOptions(); }
public SyncMap saveMapping(SyncMap map) { // TODO : check why this is needed if (map.getMapId() == null) { map.setMapId(new ObjectId()); } return syncMappings.findOneAndReplace(Filters.eq(SyncAttrs.ID, map.getMapId()), map, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
public SyncEvent saveEvent(SyncEvent event) { if (event.getEventId() == null) { event.setEventId(new ObjectId()); } return syncEvents.findOneAndReplace(Filters.eq(SyncAttrs.ID, event.getEventId()), event, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
public SyncConnectionInfo updateConnection(SyncConnectionInfo connInfo) { if(connInfo.getConnectionId() == null){ connInfo.setConnectionId(new ObjectId()); } return connectionInfo.findOneAndReplace( Filters.eq(String.valueOf(ConnectionInfoAttributes._id), connInfo.getConnectionId()), connInfo, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
@Override public FindOneAndReplaceOptions toFindOneAndReplace() { final FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(); options.bypassDocumentValidation(!validateDocuments); setMaxTime(options); setProjection(options); options.returnDocument(ret); setSort(options); options.upsert(upsert); return options; }
@Override public Observable<TDocument> findOneAndReplace(final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { return RxObservables.create(Observables.observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndReplace(filter, replacement, options, callback); } }), observableAdapter); }
@Override public Publisher<TDocument> findOneAndReplace(final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { return new ObservableToPublisher<TDocument>(observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndReplace(filter, replacement, options, callback); } })); }
@Override public Publisher<TDocument> findOneAndReplace(final ClientSession clientSession, final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { return new ObservableToPublisher<TDocument>(observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndReplace(clientSession, filter, replacement, options, callback); } })); }
public SyncUserSession saveSession(SyncUserSession userSession) { return userSessionCollection.findOneAndReplace( Filters.eq(String.valueOf(SessionAttributes._id), userSession.getSessionId()), userSession, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
public SyncNode updateNodeDetails(SyncNode nodeMapper) { return syncNodeMapping.findOneAndReplace(Filters.eq(SyncAttrs.ID, nodeMapper.getId()), nodeMapper, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER).upsert(true)); }
public SyncUser updateUser(SyncUser user) { return userDetailsCollection.findOneAndReplace( Filters.eq(String.valueOf(UserDetailAttributes._id),user.getUserid()),user, new FindOneAndReplaceOptions().returnDocument(ReturnDocument.AFTER) .upsert(true)); }
@Override public void run() { logger.info("OrclToMngSyncWriter started "+Thread.currentThread().getName()); List<Document> docs = null; FindOneAndReplaceOptions options = new FindOneAndReplaceOptions(); options.upsert(true); while(retryCount<5){ try { if(marker.isFailed()){ releaseResources(); return; } waitTime=30000; docs = dataBuffer.take(); if (docs == null || docs.isEmpty()) { continue; } if(collection==null){ refreshCollectionHandle(); } for(Document doc : docs){ if(SyncConstants.DELETE.equals(doc.get(SyncConstants.OPERATION))){ collection.findOneAndDelete(getFilter(doc)); logger.info("Document deleted"); }else{ collection.findOneAndReplace(getFilter(doc), doc, options); logger.info("Document upserted"); } } } catch (Exception e) { logger.error("Error while upserting document",e); collection =null; Mailer.sendmail(eventId, String.valueOf(docs), e, Mailer.FAILURE); retryCount++; waitTime*=retryCount; try { Thread.sleep(waitTime); } catch (InterruptedException e1) { logger.error("Thread interuupted in sleep", e1); } } } logger.info("OrclToMngSyncWriter terminated " + Thread.currentThread().getName()); }
private void setSort(final FindOneAndReplaceOptions options) { if(sort != null) { options.sort(sort); } }
private void setProjection(final FindOneAndReplaceOptions options) { if(projection != null) { options.projection(projection); } }
private void setMaxTime(final FindOneAndReplaceOptions options) { if(maxTime != null) { options.maxTime(maxTime.getLeft(), maxTime.getRight()); } }
@Override public Observable<TDocument> findOneAndReplace(final Bson filter, final TDocument replacement) { return findOneAndReplace(filter, replacement, new FindOneAndReplaceOptions()); }
@Override public Publisher<TDocument> findOneAndReplace(final Bson filter, final TDocument replacement) { return findOneAndReplace(filter, replacement, new FindOneAndReplaceOptions()); }
@Override public Publisher<TDocument> findOneAndReplace(final ClientSession clientSession, final Bson filter, final TDocument replacement) { return findOneAndReplace(clientSession, filter, replacement, new FindOneAndReplaceOptions()); }
/** * Atomically find a document and replace it. * * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * @return an Observable with a single element the document that was replaced. Depending on the value of the {@code returnOriginal} * property, this will either be the document as it was before the update or as it is after the update. * If no documents matched the query filter, then the observer will complete without emitting any items */ Observable<TDocument> findOneAndReplace(Bson filter, TDocument replacement, FindOneAndReplaceOptions options);
/** * Atomically find a document and replace it. * * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * @return a publisher with a single element the document that was replaced. Depending on the value of the {@code returnOriginal} * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned */ Publisher<TDocument> findOneAndReplace(Bson filter, TDocument replacement, FindOneAndReplaceOptions options);
/** * Atomically find a document and replace it. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * @return a publisher with a single element the document that was replaced. Depending on the value of the {@code returnOriginal} * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned * @mongodb.server.release 3.6 * @since 1.7 */ Publisher<TDocument> findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement, FindOneAndReplaceOptions options);
FindOneAndReplaceOptions toFindOneAndReplace();