/** * This is delete the single document, which is first matched */ @Override public void deleteOneDocument() { MongoDatabase db = null; MongoCollection collection = null; Bson query = null; try { db = client.getDatabase(mongo.getDataBase()); collection = db.getCollection(mongo.getSampleCollection()); query = eq("name", "sundar"); DeleteResult result = collection.deleteMany(query); if (result.wasAcknowledged()) { log.info("Single Document deleted successfully \nNo of Document Deleted : " + result.getDeletedCount()); } } catch (MongoException e) { log.error("Exception occurred while delete Single Document : " + e, e); } }
/** * This is deleted delete all document(s), which is matched */ @Override public void deleteManyDocument() { MongoDatabase db = null; MongoCollection collection = null; Bson query = null; try { db = client.getDatabase(mongo.getDataBase()); collection = db.getCollection(mongo.getSampleCollection()); query = lt("age", 20); DeleteResult result = collection.deleteMany(query); if (result.wasAcknowledged()) { log.info("Document deleted successfully \nNo of Document(s) Deleted : " + result.getDeletedCount()); } } catch (MongoException e) { log.error("Exception occurred while delete Many Document : " + e, e); } }
@Test public void shouldDeleteSession() throws Exception { // given String sessionId = UUID.randomUUID().toString(); Document sessionDocument = new Document(); given(this.mongoOperations.findById(eq(sessionId), eq(Document.class), eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME))).willReturn(Mono.just(sessionDocument)); given(this.mongoOperations.remove((Mono<? extends Object>) any(), eq("sessions"))).willReturn(Mono.just(DeleteResult.acknowledged(1))); // when StepVerifier.create(this.repository.deleteById(sessionId)) .expectNextMatches(aVoid -> { // then verify(this.mongoOperations).remove(any(Document.class), eq(ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)); return true; }); }
/** * 删除记录 * * @param collectionName * 表名 * @param mongoObj * 记录 * @return */ public static boolean deleteById(String collectionName, MongoObj mongoObj) { MongoCollection<Document> collection = getCollection(collectionName); try { Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID)); DeleteResult result = collection.deleteOne(filter); if (result.getDeletedCount() == 1) { return true; } else { return false; } } catch (Exception e) { if (log != null) { log.error("删除记录失败", e); } return false; } }
/** * Delete the data in mongo by the query. * * @param collection * the collection * @param q * the q * @param db * the db * @return the long */ public int delete(String collection, W q, String db) { int n = -1; try { MongoCollection<Document> db1 = getCollection(db, collection); if (db != null) { DeleteResult r = db1.deleteMany(q.query()); // db.remove(query); n = (int) r.getDeletedCount(); } if (log.isDebugEnabled()) { log.debug("delete, collection=" + collection + ", q=" + q + ", deleted=" + n); } } catch (Exception e) { if (log.isErrorEnabled()) log.error(e.getMessage(), e); } return n; }
@Override public DeleteResult deleteMany(Bson filter) { OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : deleteMany " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } DeleteResult retVal = collection.deleteMany(filter); stopMetric(metric, (int) retVal.getDeletedCount()); return retVal; }
@Override public DeleteResult deleteMany(Bson filter, DeleteOptions arg1) { OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : deleteMany " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } DeleteResult retVal = collection.deleteMany(filter, arg1); stopMetric(metric, (int) retVal.getDeletedCount()); return retVal; }
@Override public DeleteResult deleteOne(Bson filter) { OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : deleteOne " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } DeleteResult retVal = collection.deleteOne(filter); stopMetric(metric, (int) retVal.getDeletedCount()); return retVal; }
@Override public DeleteResult deleteOne(Bson filter, DeleteOptions arg1) { OperationMetric metric = null; if (MongoLogger.GATHERER.isEnabled()) { List<String> keyValuePairs = MongoUtilities.getKeyValuePairs(filter); String operationName = "Mongo : " + getNamespace().getCollectionName() + " : deleteOne " + MongoUtilities.filterParameters(filter).toString(); metric = startMetric(operationName, keyValuePairs); addWriteConcern(metric); } DeleteResult retVal = collection.deleteOne(filter, arg1); stopMetric(metric, (int) retVal.getDeletedCount()); return retVal; }
@Override public boolean deletePointsFromSeriesByPointKey(String key, List<String> pointKeys) { MongoCollection<Document> collection = getCollection(key); boolean ret = false; for (String pointKey : pointKeys) { Document victim = new Document(ROWKEY, key).append(COLKEY, pointKey); try { DeleteResult result = collection.deleteMany(victim); log.info("Removed " + result.getDeletedCount() + " rows"); ret = (result.getDeletedCount() > 0); } catch (MongoException me) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me)); } } return ret; }
public CompletableFuture<SecurityDefinitionStore> delete( SecurityDefinitionRequest securityDefinitionRequest) { CompletableFuture<SecurityDefinitionStore> future = new CompletableFuture<>(); // todo: handle different request types collection.deleteMany(eq("symbol", securityDefinitionRequest.getSymbol()), (DeleteResult result, final Throwable t) -> { if (t == null) { future.complete(this); } else { future.completeExceptionally(t); } }); return future; }
@Override public boolean removeSuite(DBKey dbKey, String correlationId, Long version) throws StorageException { LOGGER .debug("Removing suite with correlationId {}, version {} from {}.", correlationId, version, dbKey); MongoCollection<Document> metadata = getMetadataCollection(dbKey); final DeleteResult deleteResult = metadata.deleteOne( Filters.and( Filters.eq(CORRELATION_ID_PARAM_NAME, correlationId), Filters.eq(SUITE_VERSION_PARAM_NAME, version) )); return deleteResult.getDeletedCount() == 1; }
public void removeTilesWithIds(final StackId stackId, final List<String> tileIds) throws IllegalArgumentException { MongoUtil.validateRequiredParameter("stackId", stackId); MongoUtil.validateRequiredParameter("tileIds", tileIds); final MongoCollection<Document> tileCollection = getTileCollection(stackId); final Document tileQuery = new Document("tileId", new Document(QueryOperators.IN, tileIds)); final Document tileQueryForLog = new Document("tileId", new Document(QueryOperators.IN, Arrays.asList("list of", tileIds.size() + " tileIds"))); final DeleteResult removeResult = tileCollection.deleteMany(tileQuery); LOG.debug("removeTilesWithIds: {}.remove({}) deleted {} document(s)", MongoUtil.fullName(tileCollection), tileQueryForLog.toJson(), removeResult.getDeletedCount()); }
public void removeMatchesInvolvingObject(final MatchCollectionId collectionId, final String groupId, final String id) throws IllegalArgumentException, ObjectNotFoundException { LOG.debug("removeMatchesInvolvingObject: entry, collectionId={}, groupId={}, id={}", collectionId, groupId, id); final MongoCollection<Document> collection = getExistingCollection(collectionId); MongoUtil.validateRequiredParameter("groupId", groupId); MongoUtil.validateRequiredParameter("id", id); final Document query = getInvolvingObjectQuery(groupId, id); final DeleteResult result = collection.deleteMany(query); LOG.debug("removeMatchesInvolvingObject: removed {} matches using {}.delete({})", result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson()); }
public void removeMatchesBetweenGroups(final MatchCollectionId collectionId, final String pGroupId, final String qGroupId) throws IllegalArgumentException, ObjectNotFoundException { LOG.debug("removeMatchesBetweenGroups: entry, collectionId={}, pGroupId={}, qGroupId={}", collectionId, pGroupId, qGroupId); final MongoCollection<Document> collection = getExistingCollection(collectionId); MongoUtil.validateRequiredParameter("pGroupId", pGroupId); MongoUtil.validateRequiredParameter("qGroupId", qGroupId); final String noTileId = ""; final CanvasMatches normalizedCriteria = new CanvasMatches(pGroupId, noTileId, qGroupId, noTileId, null); final Document query = new Document( "pGroupId", normalizedCriteria.getpGroupId()).append( "qGroupId", normalizedCriteria.getqGroupId()); final DeleteResult result = collection.deleteMany(query); LOG.debug("removeMatchesBetweenGroups: removed {} matches using {}.delete({})", result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson()); }
protected final FluentFuture<Integer> doDelete( final Constraints.ConstraintHost criteria) { checkNotNull(criteria); return submit(new Callable<DeleteResult>() { @Override public DeleteResult call() { return collection().deleteMany(convertToBson(criteria)); } }).lazyTransform(new Function<DeleteResult, Integer>() { @Override public Integer apply(DeleteResult input) { return (int) input.getDeletedCount(); } }); }
public static int deleteById(MongoCollection<Document> col, Object id) { int count = 0; Bson filter = Filters.eq("_id", id); DeleteResult deleteResult = col.deleteOne(filter); count = (int) deleteResult.getDeletedCount(); return count; }
@Override long executeQuery(int threadId, long threadRunCount, long globalRunCount, long selectorId, long randomId) { final DeleteResult res = THREAD_RUN_COUNT.equals(queriedField)?mongoCollection.deleteMany(eq(queriedField, selectorId)) :ID.equals(queriedField)?mongoCollection.deleteOne(eq(queriedField, selectorId)):null; return res!=null?res.getDeletedCount():0l; }
@Override public void delete(String oid) throws DataNotFoundException { DeleteResult deleteResult = this.collection.deleteOne(eq("_id", new ObjectId(oid))); if (deleteResult.getDeletedCount() == 0) { throw new DataNotFoundException(new Throwable("File with id " + oid + " not found")); } }
@Override public void delete(String name) throws DataNotFoundException { BasicDBObject query = new BasicDBObject(); query.put("objectType", "ActivityCategory"); query.put("name", name); DeleteResult deleteResult = collection.deleteOne(query); if (deleteResult.getDeletedCount() == 0) { throw new DataNotFoundException( new Throwable("ActivityCategory {" + name + "} not found.")); } }
@Override public void delete(String id) throws DataNotFoundException { DeleteResult deleteResult = collection.deleteOne(eq("code", id)); if (deleteResult.getDeletedCount() == 0) { throw new DataNotFoundException(new Throwable("Exam Lot does not exist")); } }
@Override public void delete(String id) throws DataNotFoundException{ DeleteResult deleteResult = collection.deleteOne(eq("code", id)); if (deleteResult.getDeletedCount() == 0) { throw new DataNotFoundException(new Throwable("Transportation Lot does not exist")); } }
@Override public <T> void delete(T t) { MongoModel mongoModel = (MongoModel) t; MongoCollection<Document> collection = database.getCollection(t.getClass().getSimpleName()); BasicDBObject query = new BasicDBObject(MongoModel.OID, mongoModel.getObjectId()); DeleteResult deleteResult = collection.deleteOne(query); if (deleteResult.getDeletedCount() != 1) { Log.error("error while deleting from db, total delete count: " + deleteResult.getDeletedCount()); } }
private Object deleteByFilter(String filter) throws ServiceException { try { BasicDBObject filterObj = BasicDBObject.parse(filter); DeleteResult deleteResult = this.collection.deleteOne(filterObj); Map<String, Long> result = new HashMap<String, Long>(); result.put("delete", deleteResult.getDeletedCount()); return result; } catch (Exception e) { throw new ServiceException("Delete Exception: " + e.getMessage()); } }
private Object deleteById(ObjectId idObj) throws ServiceException { try { DeleteResult deleteResult = this.collection.deleteOne(Filters.eq("_id", idObj)); Map<String, Long> result = new HashMap<String, Long>(); result.put("delete", deleteResult.getDeletedCount()); return result; } catch (Exception e) { throw new ServiceException("Delete Exception: " + e.getMessage()); } }
private void deleteLog(Date olderThan) { MongoCollection<Log> logCollection = mongoService.getMongoClient().getDatabase(database).getCollection(collection, Log.class); Bson filter = Filters.lt("timeStamp", olderThan); logCollection.find(filter).forEach((Block<? super Log>) log -> { log.getLogFiles().forEach(logFile -> { GridFSBucket gridFSBucket = GridFSBuckets.create(mongoService.getMongoClient().getDatabase(database), logFile.getBucket()); gridFSBucket.delete(logFile.getFileObjectId()); }); }); DeleteResult deleteResult = logCollection.deleteMany(filter); }
public static void deleteDocument(Bson filter, Optional<String> hash, MongoCollection<Document> collection) { if (hash.isPresent()) { filter = Filters.and( filter, Filters.eq("meta.hash", hash.get()) ); } final DeleteResult result = collection.deleteOne(filter); if (result.getDeletedCount() != 1) { throw new WebApplicationException("Concurrent modification", 422); } }
/** * Removes the desired data from the database * * @param removeKey JSONObject containing information regarding what data that needs to be removed * @return true or false depending on success */ @Override public synchronized boolean removeDataFromDatabase (JSONObject removeKey){ MongoCollection<Document> collection = db.getCollection("requestTable"); BasicDBObject dbObject = (BasicDBObject) JSON.parse(removeKey.toString()); DeleteResult removeReturn = collection.deleteOne(dbObject); return removeReturn.wasAcknowledged(); }
/** * Removes user from database * * @param removeKey JSONObject containing data about the user that is to be removed * @return Returns true if successful and false if it failed. */ @Override public synchronized boolean removeUserFromDatabase (JSONObject removeKey){ MongoCollection<Document> collection = db.getCollection("userTable"); BasicDBObject dbObject = (BasicDBObject) JSON.parse(removeKey.toString()); DeleteResult removeReturn = collection.deleteOne(dbObject); return removeReturn.wasAcknowledged(); }
@Override public boolean deletePointsFromSeries(String key) { boolean ret = false; MongoCollection<Document> collection = getCollection(key); Document victim = new Document(ROWKEY, key); try { DeleteResult result = collection.deleteMany(victim); log.info("Removed " + result.getDeletedCount() + " rows"); ret = (result.getDeletedCount() > 0); } catch (MongoException me) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me)); } unregisterKey(key); return ret; }
@Override public Boolean deleteBlob(CallingContext context, String docPath) { log.debug("Removing " + docPath); Document query = new Document(); query.append(BLOB_NAME, docPath); try { DeleteResult res = getCollection().deleteOne(query); return res.getDeletedCount() != 0; } catch (MongoException e) { log.error("Could not delete " + docPath + ": " + e.getMessage()); log.debug(ExceptionToString.format(e)); } return false; }
private Boolean releaseLockWithID(String lockName, String id) { Document lockFileQuery = new Document(); lockFileQuery.put("_id", id); MongoCollection<Document> coll = getLockCollection(lockName); DeleteResult res = coll.deleteOne(lockFileQuery); return (res.getDeletedCount() == 1); }
public CompletableFuture<DeleteResult> delete(final String collectionName, final String objectId) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return dbExecutor.delete(collectionName, objectId); } }); }
public CompletableFuture<DeleteResult> delete(final String collectionName, final ObjectId objectId) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return dbExecutor.delete(collectionName, objectId); } }); }
public CompletableFuture<DeleteResult> deleteOne(final String collectionName, final Bson filter) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return dbExecutor.deleteOne(collectionName, filter); } }); }
public CompletableFuture<DeleteResult> deleteAll(final String collectionName, final Bson filter) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return dbExecutor.deleteAll(collectionName, filter); } }); }
public CompletableFuture<DeleteResult> delete(final String objectId) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return collExecutor.delete(objectId); } }); }
public CompletableFuture<DeleteResult> delete(final ObjectId objectId) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return collExecutor.delete(objectId); } }); }
public CompletableFuture<DeleteResult> deleteOne(final Bson filter) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return collExecutor.deleteOne(filter); } }); }
public CompletableFuture<DeleteResult> deleteAll(final Bson filter) { return asyncExecutor.execute(new Callable<DeleteResult>() { @Override public DeleteResult call() throws Exception { return collExecutor.deleteAll(filter); } }); }