com.mongodb.client.result.DeleteResult Java Examples

The following examples show how to use com.mongodb.client.result.DeleteResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicInteractionTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
void testMultipleDocumentDeletionWithOptions() {
    ReactiveMongoDatabase database = client.getDatabase(DATABASE);
    ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));

    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents).await().indefinitely();

    DeleteResult result = collection.deleteMany(gte("i", 90), new DeleteOptions().collation(
            Collation.builder().locale("en").caseLevel(true).build()))
            .await().indefinitely();
    assertThat(result.getDeletedCount()).isEqualTo(10);
    assertThat(collection.find(eq("i", 90)).collectItems().first().await().asOptional().indefinitely()).isEmpty();
    Long count = collection.countDocuments().await().indefinitely();
    assertThat(count).isEqualTo(90);
}
 
Example #2
Source File: BasicInteractionTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
void testMultipleDocumentDeletion() {
    ReactiveMongoDatabase database = client.getDatabase(DATABASE);
    ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));

    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents).await().indefinitely();

    DeleteResult result = collection.deleteMany(gte("i", 90)).await().indefinitely();
    assertThat(result.getDeletedCount()).isEqualTo(10);
    assertThat(collection.find(eq("i", 90)).collectItems().first().await().indefinitely()).isNull();
    Long count = collection.countDocuments().await().indefinitely();
    assertThat(count).isEqualTo(90);
}
 
Example #3
Source File: BasicInteractionTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
void testSingleDocumentDeletionWithOptions() {
    ReactiveMongoDatabase database = client.getDatabase(DATABASE);
    ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));

    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents).await().indefinitely();

    DeleteResult result = collection.deleteOne(eq("i", 10),
            new DeleteOptions().collation(
                    Collation.builder().locale("en").caseLevel(true).build()))
            .await().indefinitely();
    assertThat(result.getDeletedCount()).isEqualTo(1);
    assertThat(collection.find(eq("i", 10)).collectItems().first().await().indefinitely()).isNull();
    Long count = collection.countDocuments().await().indefinitely();
    assertThat(count).isEqualTo(99);
}
 
Example #4
Source File: BasicInteractionTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
void testSingleDocumentDeletion() {
    ReactiveMongoDatabase database = client.getDatabase(DATABASE);
    ReactiveMongoCollection<Document> collection = database.getCollection(randomAlphaString(8));

    List<Document> documents = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        documents.add(new Document("i", i));
    }
    collection.insertMany(documents).await().indefinitely();

    DeleteResult result = collection.deleteOne(eq("i", 10)).await().indefinitely();
    assertThat(result.getDeletedCount()).isEqualTo(1);
    assertThat(collection.find(eq("i", 10)).collectItems().first().await().indefinitely()).isNull();
    Long count = collection.countDocuments().await().indefinitely();
    assertThat(count).isEqualTo(99);
}
 
Example #5
Source File: AuthorGroupServiceImpl.java    From biliob_backend with MIT License 6 votes vote down vote up
@Override
public Result<DeleteResult> deleteAuthorList(String objectId) {
    ObjectId userId = UserUtils.getUserId();
    if (userId == null) {
        return new Result<>(ResultEnum.HAS_NOT_LOGGED_IN);
    }
    AuthorGroup authorGroup = this.getAuthorList(objectId);

    if (authorGroup == null) {
        return new Result<>(ResultEnum.LIST_NOT_FOUND);
    }
    if (authorGroup.getMaintainer().getId().toHexString().equals(userId.toHexString())) {
        return new Result<>(ResultEnum.SUCCEED, mongoTemplate.remove(Query.query(Criteria.where("_id").is(objectId)), AuthorGroup.class));
    } else {
        return new Result<>(ResultEnum.EXECUTE_FAILURE);
    }
}
 
Example #6
Source File: MatchDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
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);

    validateRequiredGroupIds(pGroupId, qGroupId);
    final MongoCollection<Document> collection = getExistingCollection(collectionId);
    final Document query = getNormalizedGroupIdQuery(pGroupId, qGroupId);

    final DeleteResult result = collection.deleteMany(query);

    LOG.debug("removeMatchesBetweenGroups: removed {} matches using {}.delete({})",
              result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
 
Example #7
Source File: MongodbManager.java    From grain with MIT License 6 votes vote down vote up
/**
 * 删除记录
 * 
 * @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;
	}

}
 
Example #8
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<DeleteResult> deleteOne(final Bson filter, final DeleteOptions options) {
    return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) {
                    wrapped.deleteOne(filter, options, callback);
                }
            }));
}
 
Example #9
Source File: MongoDbDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeCollection(MagicCollection c) throws SQLException {
	logger.debug("remove collection " + c);
	BasicDBObject query = new BasicDBObject();
	query.put(dbColIDField, c.getName());
	DeleteResult dr = db.getCollection(colCards).deleteMany(query);
	logger.trace(dr);
	db.getCollection(colCollects, MagicCollection.class).deleteOne(Filters.eq("name", c.getName()));
}
 
Example #10
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example #11
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
private <T> OpResult removeObject(MongoCollection<Document> collection, String nameField, String name) {
    BsonDocument filter = new BsonDocument();
    filter.append(nameField, new BsonString(name));
    DeleteResult dr = collection.deleteOne(filter);
    OpResult result = new OpResult();
    result.code = 200;
    result.message = String.format(" %d config item removed!", dr.getDeletedCount());
    return result;
}
 
Example #12
Source File: MongoCollectionImpl.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public long delete(Bson filter) {
    var watch = new StopWatch();
    long deletedRows = 0;
    try {
        DeleteResult result = collection().deleteMany(filter == null ? new BsonDocument() : filter);
        deletedRows = result.getDeletedCount();
        return deletedRows;
    } finally {
        long elapsed = watch.elapsed();
        ActionLogContext.track("mongo", elapsed, 0, (int) deletedRows);
        logger.debug("delete, collection={}, filter={}, deletedRows={}, elapsed={}", collectionName, new BsonLogParam(filter, mongo.registry), deletedRows, elapsed);
        checkSlowOperation(elapsed);
    }
}
 
Example #13
Source File: MongoCollectionImpl.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delete(Object id) {
    var watch = new StopWatch();
    long deletedRows = 0;
    try {
        DeleteResult result = collection().deleteOne(Filters.eq("_id", id));
        deletedRows = result.getDeletedCount();
        return deletedRows == 1;
    } finally {
        long elapsed = watch.elapsed();
        ActionLogContext.track("mongo", elapsed, 0, (int) deletedRows);
        logger.debug("delete, collection={}, id={}, elapsed={}", collectionName, id, elapsed);
        checkSlowOperation(elapsed);
    }
}
 
Example #14
Source File: MongoDbDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeCard(MagicCard mc, MagicCollection collection) throws SQLException {
	logger.debug("removeCard " + mc + " from " + collection);

	BasicDBObject andQuery = new BasicDBObject();
	List<BasicDBObject> obj = new ArrayList<>();
	obj.add(new BasicDBObject(dbIDField, IDGenerator.generate(mc)));
	obj.add(new BasicDBObject(dbColIDField, collection.getName()));
	andQuery.put("$and", obj);
	DeleteResult dr = db.getCollection(colCards, BasicDBObject.class).deleteMany(andQuery);
	logger.debug(dr.toString());

}
 
Example #15
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<DeleteResult> deleteOne(final Bson filter) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<DeleteResult>>() {
        @Override
        public void apply(final SingleResultCallback<DeleteResult> callback) {
            wrapped.deleteOne(filter, callback);
        }
    }), observableAdapter);
}
 
Example #16
Source File: DatastoreImpl.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the given entity (by @Id), with the WriteConcern
 *
 * @param entity  the entity to delete
 * @param options the options to use when deleting
 * @return results of the delete
 */
@Override
public <T> DeleteResult delete(final T entity, final DeleteOptions options) {
    if (entity instanceof Class<?>) {
        throw new MappingException("Did you mean to delete all documents? -- ds.createQuery(???.class).delete()");
    }
    return find(entity.getClass())
               .filter(eq("_id", mapper.getId(entity)))
               .delete(options);
}
 
Example #17
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<DeleteResult> deleteMany(final Bson filter, final DeleteOptions options) {
    return RxObservables.create(Observables.observe(new Block<SingleResultCallback<DeleteResult>>() {
        @Override
        public void apply(final SingleResultCallback<DeleteResult> callback) {
            wrapped.deleteMany(filter, options, callback);
        }
    }), observableAdapter);
}
 
Example #18
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<DeleteResult> deleteMany(final Bson filter, final DeleteOptions options) {
    return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) {
                    wrapped.deleteMany(filter, options, callback);
                }
            }));
}
 
Example #19
Source File: ReactiveStreamsMongoLockProviderIntegrationTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLockWhenDocumentRemovedExternally() {
    LockProvider provider = getLockProvider();
    assertThat(provider.lock(lockConfig(LOCK_NAME1))).isNotEmpty();
    assertLocked(LOCK_NAME1);

    DeleteResult result = execute(getLockCollection().deleteOne(eq(ID, LOCK_NAME1)));

    assumeThat(result.getDeletedCount()).isEqualTo(1);

    assertThat(provider.lock(lockConfig(LOCK_NAME1))).isNotEmpty();
    assertLocked(LOCK_NAME1);
}
 
Example #20
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<DeleteResult> deleteOne(final ClientSession clientSession, final Bson filter, final DeleteOptions options) {
    return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) {
                    wrapped.deleteOne(clientSession.getWrapped(), filter, options, callback);
                }
            }));
}
 
Example #21
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
public Future<@Nullable MongoClientDeleteResult> removeDocumentWithOptions(String collection, JsonObject query, @Nullable WriteOption writeOption) {
  requireNonNull(collection, "collection cannot be null");
  requireNonNull(query, "query cannot be null");

  MongoCollection<JsonObject> coll = getCollection(collection, writeOption);
  Bson bquery = wrap(encodeKeyWhenUseObjectId(query));
  Promise<DeleteResult> promise = vertx.promise();
  coll.deleteOne(bquery).subscribe(new SingleResultSubscriber<>(promise));
  return promise.future().map(Utils::toMongoClientDeleteResult);
}
 
Example #22
Source File: MongoDbDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deleteOrderEntry(List<OrderEntry> state) throws SQLException {
	logger.debug("remove " + state + " item(s) in orders");
	for (OrderEntry s : state) {
		Bson filter = new Document(dbOrdersField+".id", s.getId());
		DeleteResult res = db.getCollection(colOrders).deleteOne(filter);
		logger.debug(res.getDeletedCount() + " item deleted");
	}
}
 
Example #23
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DeleteResult deleteDocument(String keyName, String keyValue) {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		DeleteResult result = collection.deleteMany(new BasicDBObject(keyName,
				keyValue));
		log.debug(result.toString());

		return result;
	}
 
Example #24
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<DeleteResult> deleteMany(final ClientSession clientSession, final Bson filter, final DeleteOptions options) {
    return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) {
                    wrapped.deleteMany(clientSession.getWrapped(), filter, options, callback);
                }
            }));
}
 
Example #25
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void removeTile(final StackId stackId,
                       final String tileId)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("tileId", tileId);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document tileQuery = new Document("tileId", tileId);
    final DeleteResult removeResult = tileCollection.deleteOne(tileQuery);

    LOG.debug("removeTile: {}.remove({}) deleted {} document(s)",
              MongoUtil.fullName(tileCollection), tileQuery.toJson(), removeResult.getDeletedCount());
}
 
Example #26
Source File: MatchDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public void removeMatchesOutsideGroup(final MatchCollectionId collectionId,
                                      final String groupId)
        throws IllegalArgumentException, ObjectNotFoundException {

    MongoUtil.validateRequiredParameter("groupId", groupId);
    final MongoCollection<Document> collection = getExistingCollection(collectionId);
    final Document query = getOutsideGroupQuery(groupId);

    final DeleteResult result = collection.deleteMany(query);

    LOG.debug("removeMatchesOutsideGroup: removed {} matches using {}.delete({})",
              result.getDeletedCount(), MongoUtil.fullName(collection), query.toJson());
}
 
Example #27
Source File: MongoApprovalRepositoryImpl.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Override
public boolean deleteByUserIdAndClientIdAndScope(final MongoApproval mongoApproval) {
    final DeleteResult deleteResult = mongoTemplate.remove(byUserIdAndClientIdAndScope(mongoApproval),
            MongoApproval.class);

    return deleteResult.wasAcknowledged();
}
 
Example #28
Source File: LotteryCollection.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Mono<DeleteResult> resetJackpot() {
    LOGGER.debug("[Lottery] Jackpot deletion");

    return Mono.from(this.getCollection()
            .deleteOne(Filters.eq("_id", "jackpot")))
            .doOnNext(result -> LOGGER.trace("[Lottery] Jackpot deletion result: {}", result))
            .doOnTerminate(() -> DB_REQUEST_COUNTER.labels(LotteryCollection.NAME).inc());
}
 
Example #29
Source File: PersonServiceWithMongo.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
    DeleteResult result = peopleCollection.deleteOne(eq("id", id));
    if (result.getDeletedCount() != 1)
        personNotFound(id);
}
 
Example #30
Source File: MongoDBClient.java    From redtorch with MIT License 5 votes vote down vote up
/**
 * 通过过滤条件删除数据
 * 
 * @param dbName
 * @param collectionName
 * @param filter
 * @return
 */
public boolean delete(String dbName, String collectionName, Document filter) {
	if (filter != null) {
		DeleteResult result = mongoClient.getDatabase(dbName).getCollection(collectionName)
				.deleteMany(new Document(filter));
		long deletedCount = result.getDeletedCount();
		return deletedCount > 0 ? true : false;
	}
	return false;
}