@Override public Optional<T> call() throws Exception { @Nullable T result = collection().findOneAndReplace( convertToBson(criteria), // query document, options); return Optional.fromNullable(result); } });
@Override public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { FindOneAndReplaceOptions opts = new FindOneAndReplaceOptions(); opts.sort(sort); opts.collation(collation); opts.projection(fields); if (options.isUpsert()) { opts.upsert(true); } if (options.isReturnNew()) { opts.returnDocument(ReturnDocument.AFTER); } return collection.findOneAndReplace(query, update, opts); } }
public void update(ServerConfiguration configuration, final MongoCollection mongoCollection, final Document mongoDocument) { Task task = mongoClient -> { MongoDatabase mongoDatabase = mongoCollection.getParentDatabase(); com.mongodb.client.MongoDatabase database = mongoClient.getDatabase(mongoDatabase.getName()); com.mongodb.client.MongoCollection<Document> collection = database.getCollection(mongoCollection.getName()); if (!mongoDocument.containsKey("_id")) { collection.insertOne(mongoDocument); } else { collection.findOneAndReplace( new Document("_id", mongoDocument.get("_id")), mongoDocument, new FindOneAndReplaceOptions().upsert(true)); } }; executeTask(configuration, task); }
@Override public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { FindOneAndReplaceOptions opts = new FindOneAndReplaceOptions(); opts.sort(sort); opts.collation(collation); opts.projection(fields); if (options.isUpsert()) { opts.upsert(true); } if (options.isReturnNew()) { opts.returnDocument(ReturnDocument.AFTER); } return collection.findOneAndReplace(query, update, opts); } }
@Override public Optional<T> call() throws Exception { @Nullable T result = collection().findOneAndReplace( convertToBson(criteria), // query document, options); return Optional.fromNullable(result); } });
public static void saveNode(String job_id, String key, JSONObject metadata){ Map<String, Object> props = new HashMap<>(); metadata.keySet().forEach(prop -> props.put(prop, metadata.get(prop))); props.put("_id", getDbKey(job_id, key)); props.put("_job_id", job_id); db.getCollection("nodes").findOneAndReplace(eq("_id", getDbKey(job_id, key)), new Document(props), UPSERT); }
@Override @Nullable public TDocument findOneAndReplace(@NotNull ClientSession clientSession, @NotNull Bson filter, @NotNull TDocument replacement) { maybeThrowExceptionBeforeUpdate(); TDocument doc = collection.findOneAndReplace(clientSession, filter, replacement); maybeThrowExceptionAfterUpdate(); return doc; }
@Override @Nullable public TDocument findOneAndReplace(@NotNull ClientSession clientSession, @NotNull Bson filter, @NotNull TDocument replacement, @NotNull FindOneAndReplaceOptions options) { maybeThrowExceptionBeforeUpdate(); TDocument doc = collection.findOneAndReplace(clientSession, filter, replacement, options); maybeThrowExceptionAfterUpdate(); return doc; }
@Override @Nullable public TDocument findOneAndReplace(@NotNull Bson filter, @NotNull TDocument replacement, @NotNull FindOneAndReplaceOptions options) { maybeThrowExceptionBeforeUpdate(); TDocument doc = collection.findOneAndReplace(filter, replacement, options); maybeThrowExceptionAfterUpdate(); return doc; }
public static void saveDocument(String collection, String _id, Document doc) throws CodecConfigurationException { open();//ensure connection is open doc.put("_id", _id); Boolean present = hasId(collection, _id); if(present) { db.getCollection(collection).findOneAndReplace(eq("_id", _id), doc);//replace existing document } else { insertDocument(collection, doc);//insert a new document } }
@Override public void saveObject(T instance) { // Null check if (instance == null) { plugin.logError("MongoDB database request to store a null. "); return; } if (!(instance instanceof DataObject)) { plugin.logError("This class is not a DataObject: " + instance.getClass().getName()); return; } DataObject dataObj = (DataObject)instance; try { Gson gson = getGson(); String toStore = gson.toJson(instance); // Change uniqueId to _id toStore = toStore.replaceFirst(UNIQUEID, MONGO_ID); // This parses JSON to a Mongo Document Document document = Document.parse(toStore); // Filter based on the id Bson filter = new Document(MONGO_ID, dataObj.getUniqueId()); // Set the options to upsert (update or insert if doc is not there) FindOneAndReplaceOptions options = new FindOneAndReplaceOptions().upsert(true); // Do the deed collection.findOneAndReplace(filter, document, options); } catch (Exception e) { plugin.logError("Could not save object " + instance.getClass().getName() + " " + e.getMessage()); } }
@Override @Nullable public TDocument findOneAndReplace(@NotNull Bson filter, @NotNull TDocument replacement) { maybeThrowExceptionBeforeUpdate(); TDocument doc = collection.findOneAndReplace(filter, replacement); maybeThrowExceptionAfterUpdate(); return doc; }
void setDeploymentInfo(String environment, String botId, Integer botVersion, DeploymentInfo.DeploymentStatus deploymentStatus) { Document filter = new Document(); filter.put("environment", environment); filter.put("botId", botId); filter.put("botVersion", botVersion); Document newDeploymentInfo = new Document(filter); newDeploymentInfo.put("deploymentStatus", deploymentStatus.toString()); Document replacedDocument = collection.findOneAndReplace(filter, newDeploymentInfo); if (replacedDocument == null) { collection.insertOne(newDeploymentInfo); } }
@Override public Suite replaceSuite(Suite oldSuite, Suite newSuite) throws StorageException { MongoCollection<Document> metadata = getMetadataCollection(new SimpleDBKey(oldSuite)); LOGGER.debug("Replacing suite {} in metadata collection.", oldSuite); metadata.findOneAndReplace(Document.parse(oldSuite.toJson()),Document.parse(newSuite.toJson())); return newSuite; }
@Override public Suite replaceSuite(Suite oldSuite, Suite newSuite) throws StorageException { MongoCollection<Document> metadata = getMetadataCollection(new SimpleDBKey(oldSuite)); LOGGER.debug("Replacing suite {} in metadata collection.", oldSuite); metadata.findOneAndReplace(Document.parse(oldSuite.toJson()),Document.parse(newSuite.toJson())); return newSuite; }
public void updateIfMatch(final V value, final String eTag) { Bson query = and(eq(AbstractMongoRepository.ID, keyOf(value)), eq(ETAG, eTag)); Document updatedETaggable = collection().findOneAndReplace(query, encode(value), new FindOneAndReplaceOptions().returnDocument(AFTER)); if (isNull(updatedETaggable)) { Optional<V> findById = findOne(keyOf(value)); if (findById.isPresent()) { throw new ConcurrentModificationException("Entity concurrently modified: " + keyOf(value)); } throw new NotFoundException("Entity does not exist: " + keyOf(value)); } }
public void save() throws StorageException { MongoCollection<Document> objectMetaCol = getObjectMetadataCollection(); MongoCollection<Document> metaCol = getMetaCollection(); boolean isInStorage = existsInStorage(); if (!isInStorage) { getObjectMetadata(); mergeMetaProp(); objectMetaCol.insertOne(getEscapedDoc(objectMetadata)); getRecordMetadata(); metaCol.insertOne(getEscapedDoc(recordMetadata)); } else { objectMetadata.put("date_object_modified", df.print(new Date().getTime())); mergeMetaProp(); // full replacement of object metadata... objectMetaCol.findOneAndReplace(eq("redboxOid", oid), getEscapedDoc(objectMetadata)); // full replacement of record metadata... metaCol.findOneAndReplace(eq("redboxOid", oid), getEscapedDoc(recordMetadata)); } }
@Override public void appendSnapshot(MongoCollection<Document> snapshotCollection, DomainEventMessage<?> snapshot, Serializer serializer) { snapshotCollection.findOneAndReplace(new BsonDocument(eventConfiguration.aggregateIdentifierProperty(), new BsonString(snapshot.getAggregateIdentifier())), createSnapshotDocument(snapshot, serializer), new FindOneAndReplaceOptions().upsert(true)); }
@Override public void appendSnapshot(MongoCollection<Document> snapshotCollection, DomainEventMessage<?> snapshot, Serializer serializer) { snapshotCollection.findOneAndReplace(new BsonDocument(eventConfiguration.aggregateIdentifierProperty(), new BsonString(snapshot.getAggregateIdentifier())), createSnapshotDocument(snapshot, serializer), new FindOneAndReplaceOptions().upsert(true)); }
@Override public void update(final Entity old, final Entity updated) throws StaleUpdateException, EntityStorageException { requireNonNull(old); requireNonNull(updated); // The updated entity must have the same Subject as the one it is replacing. if(!old.getSubject().equals(updated.getSubject())) { throw new EntityStorageException("The old Entity and the updated Entity must have the same Subject. " + "Old Subject: " + old.getSubject().getData() + ", Updated Subject: " + updated.getSubject().getData()); } // Make sure the updated Entity has a higher verison. if(old.getVersion() >= updated.getVersion()) { throw new EntityStorageException("The old Entity's version must be less than the updated Entity's version." + " Old version: " + old.getVersion() + " Updated version: " + updated.getVersion()); } final Set<Bson> filters = new HashSet<>(); // Must match the old entity's Subject. filters.add( makeSubjectFilter(old.getSubject()) ); // Must match the old entity's Version. filters.add( makeVersionFilter(old.getVersion()) ); // Do a find and replace. final Bson oldEntityFilter = Filters.and(filters); final Document updatedDoc = ENTITY_CONVERTER.toDocument(updated); final MongoCollection<Document> collection = mongo.getDatabase(ryaInstanceName).getCollection(COLLECTION_NAME); if(collection.findOneAndReplace(oldEntityFilter, updatedDoc) == null) { throw new StaleUpdateException("Could not update the Entity with Subject '" + updated.getSubject().getData() + "."); } }