private FindOneAndUpdateOptions convertToFindOneAndUpdateOptions(FindAndModifyOptions options, Document fields, Document sort) { FindOneAndUpdateOptions result = new FindOneAndUpdateOptions(); result = result.projection(fields).sort(sort).upsert(options.isUpsert()); if (options.isReturnNew()) { result = result.returnDocument(ReturnDocument.AFTER); } else { result = result.returnDocument(ReturnDocument.BEFORE); } result = options.getCollation().map(Collation::toMongoCollation).map(result::collation).orElse(result); return result; } }
private void initializeClusterInstanceVersion() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> instances = database.getCollection(CONSTANTS_TB_INSTS); Bson condition = Filters.eq("_id", this.endpoint); Document increases = new Document(); increases.append("version", 1L); Document document = new Document(); document.append("$inc", increases); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.upsert(true); Document target = instances.findOneAndUpdate(condition, document, new FindOneAndUpdateOptions().upsert(true)); this.instanceVersion = (target == null) ? 1 : (target.getLong("version") + 1); }
/** * Performs an upsert. If query will match a document, then it will be modified and old or new * version of document returned (depending if {@link #returningNew()} was configured). When * there * isn't any such matching document, a new one will be created and returned if * {@link #returningNew()} was configured. * <p> * <em>Note: Upsert operation requires special care to set or init all required attributes * (including but not limited to '_id'), so that valid document could be inserted into collection. * </em> * @return future of optional document. * */ public final FluentFuture<Optional<T>> upsert() { options.upsert(true); options.sort(convertToBson(ordering)); // TODO exclusion / projection return repository.doModify(criteria, collectRequiredUpdate(), options); }
Document query = new Document("id", 2); Document setOnInsert = new Document(); setOnInsert.put("date", new Date()); setOnInsert.put("reptype", "EOD"); Document update = new Document("$setOnInsert", setOnInsert); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.returnDocument(ReturnDocument.AFTER); options.upsert(true); db.getCollection("COL1").findOneAndUpdate(query, update, options);
public synchronized void persistToStore() { if (!config.persistent || lastVal == null) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Persisting lastVal={} to store, collection: {}", lastVal, config.collection); } BasicDBObject updateObj = new BasicDBObject().append("$set", new BasicDBObject(config.field, lastVal)); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER); trackingObj = dbCol.findOneAndUpdate(trackingObj, updateObj, options); }
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .sort( sort ) .bypassDocumentValidation( ( bypass != null ? bypass : false ) ) .upsert( ( upsert != null ? upsert : false ) ) .projection( fields ) .returnDocument( ( returnNewDocument != null ? returnNewDocument : false ) ? ReturnDocument.AFTER : ReturnDocument.BEFORE ) .maxTime( 0, TimeUnit.MILLISECONDS ); theOne = collection.withWriteConcern( (wc != null ? wc : collection.getWriteConcern() ) ).findOneAndUpdate( query, update, options );
/** * Updates a single document that matches. * @return number of updated documents. 0 or 1 */ public FluentFuture<Integer> updateFirst() { return repository.doUpdateFirst(criteria, collectRequiredUpdate(), new FindOneAndUpdateOptions()); }
@Override public long decrement(String aCounterName) { Document doc = collection .findOneAndUpdate( eq("_id", aCounterName), inc(DSL.VALUE, -1), new FindOneAndUpdateOptions() .returnDocument(AFTER) .projection(include(DSL.VALUE)) ); if (doc == null) { throw new IllegalArgumentException("Counter not found: " + aCounterName); } return doc.getLong(DSL.VALUE); }
@Nonnull @Override public <V> Optional<V> valueFor(SingleFeatureBean feature, V value) { checkNotNull(feature, "feature"); checkNotNull(value, "value"); final String ownerId = idConverter.convert(feature.owner()); final String featureId = Integer.toString(feature.id()); final String fieldName = concat(ModelDocument.F_SINGLE_FEATURE, featureId); final Bson filter = eq(ModelDocument.F_ID, ownerId); final Bson projection = include(fieldName); final Bson update = set(fieldName, serializeValue(value)); final ModelDocument instance = documents.findOneAndUpdate(filter, update, new FindOneAndUpdateOptions().upsert(true).projection(projection)); return Optional.ofNullable(instance) .map(ModelDocument::getSingleFeatures) .map(l -> l.get(featureId)) .map(this::deserializeValue); }
@Test public void testFindOneAndUpdateSorted() throws Exception { collection.insertOne(json("_id: 1, a: 15")); collection.insertOne(json("_id: 2, a: 10")); collection.insertOne(json("_id: 3, a: 20")); Document order = json("a: 1"); Document result = collection.findOneAndUpdate(json(""), json("$inc: {a: 1}"), new FindOneAndUpdateOptions().sort(order).returnDocument(ReturnDocument.AFTER)); assertThat(result).isEqualTo(json("_id: 2, a: 11")); order = json("a: -1"); result = collection.findOneAndUpdate(json(""), json("$inc: {a: 1}"), new FindOneAndUpdateOptions().sort(order).returnDocument(ReturnDocument.AFTER)); assertThat(result).isEqualTo(json("_id: 3, a: 21")); }
@Nonnull @Override public <V> Optional<V> valueFor(ManyFeatureBean feature, V value) { checkNotNull(feature, "feature"); checkNotNull(value, "value"); final String ownerId = idConverter.convert(feature.owner()); final String featureId = Integer.toString(feature.id()); final String fieldName = concat(ModelDocument.F_MANY_FEATURE, featureId); final String fieldNameWithPos = concat(fieldName, Integer.toString(feature.position())); final Bson filter = and(eq(ModelDocument.F_ID, ownerId), exists(fieldNameWithPos)); final Bson projection = slice(fieldName, feature.position(), 1); final Bson update = set(fieldNameWithPos, serializeValue(value)); final ModelDocument instance = documents.findOneAndUpdate(filter, update, new FindOneAndUpdateOptions().projection(projection)); final Optional<V> previousValue = Optional.ofNullable(instance) .map(ModelDocument::getManyFeatures) .map(m -> m.get(featureId)) .filter(l -> !l.isEmpty()) .map(l -> l.get(0)) .map(this::deserializeValue); if (!previousValue.isPresent()) { throw new IndexOutOfBoundsException(); } return previousValue; }
/** * Configures this modifier so that new (updated) version of document will be returned in * case of successful update. * @see #returningOld() * @return {@code this} modifier for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final M returningNew() { options.returnDocument(ReturnDocument.AFTER); return (M) this; }
/** * Performs an update. If query will match a document, then it will be modified and old or new * version of document returned (depending if {@link #returningNew()} was configured). When * there * isn't any matching document, {@link Optional#absent()} will be result of the operation. * @return future of optional document (present if matching document would be found) */ public final FluentFuture<Optional<T>> update() { options.sort(convertToBson(ordering)); // TODO exlusion / projection return repository.doModify(criteria, collectRequiredUpdate(), options); } }
@Test public void testFindOneAndUpdateUpsert() { Document result = collection.findOneAndUpdate(json("_id: 1"), json("$inc: {a: 1}"), new FindOneAndUpdateOptions().upsert(true).returnDocument(ReturnDocument.AFTER)); assertThat(result).isEqualTo(json("_id: 1, a: 1")); assertThat(collection.find().first()).isEqualTo(json("_id: 1, a: 1")); }
@Override public void mark(String digest) { Document dbFile = filesColl.findOneAndUpdate(Filters.eq(METADATA_PROPERTY_FILENAME, digest), Updates.set(String.format("%s.%s", METADATA_PROPERTY_METADATA, msKey), TRUE), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); if (dbFile != null) { status.numBinaries += 1; status.sizeBinaries += dbFile.getLong(METADATA_PROPERTY_LENGTH); } }
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions() .sort( sort ) .bypassDocumentValidation( ( bypass != null ? bypass : false ) ) .upsert( ( upsert != null ? upsert : false ) ) .projection( fields ) .returnDocument( ( returnNewDocument != null ? returnNewDocument : false ) ? ReturnDocument.AFTER : ReturnDocument.BEFORE ) .maxTime( 0, TimeUnit.MILLISECONDS ); theOne = collection.withWriteConcern( (wc != null ? wc : collection.getWriteConcern() ) ).findOneAndUpdate( query, update, options );
@Override public void set(String aCounterName, long aValue) { collection .findOneAndUpdate( eq("_id", aCounterName), combine( Updates.set(DSL.VALUE, aValue), setOnInsert("_id", aCounterName), setOnInsert(DSL.CREATE_TIME, new Date()) ), new FindOneAndUpdateOptions() .upsert(true) ); }
@Override @Nullable public TDocument findOneAndUpdate(final Bson filter, final Bson update) { return findOneAndUpdate(filter, update, new FindOneAndUpdateOptions()); }
FindOneAndUpdateOptions updateOptions = new FindOneAndUpdateOptions() .projection(fields).upsert(true);
/** * Configures this modifier so that old (not updated) version of document will be returned in * case of successful update. * This is default behavior so it may be called only for explanatory reasons. * @see #returningNew() * @return {@code this} modifier for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final M returningOld() { options.returnDocument(ReturnDocument.BEFORE); return (M) this; }