Home > Blockchain >  ReactiveMongoTemplate does not return number of documents removed
ReactiveMongoTemplate does not return number of documents removed

Time:12-30

I have this implementation to remove documents based on some id using ReactiveMongoTemplate. I'm trying to get the size of the the list of impacted documents but it always returns 0, and since it is reactive I'm not sure how to get the number of records deleted

@Override
public int deleteMongoDataForGivenId(Long id) {
     int deletedRecords = 0;
     Query query = new Query();
     query.addCriteria(where("id").is(id));

     Flux<Object> deletedDocs = reactiveMongoTemplate.findAllAndRemove(query, Object.class, "SomeCollection");

     if(!deletedDocs.collectList().block().isEmpty()) {
          List<Object> listOfRecords = deletedDocs.collectList().block();
          deletedRecords = listOfRecords.size();
     }
}

CodePudding user response:

Doing it the reactive way would be to return a Mono<Long> instead of blocking and unpacking the mono into an long or int:

public Mono<Long> deleteMongoDataForGivenId(Long id) {
    Query query = new Query();
    query.addCriteria(where("id").is(id));

    return reactiveMongoTemplate
            .findAllAndRemove(query, MyDocument.class, "SomeCollection")
            .count();
}

Having to use a blocking method defies the purpose of reactive programming, but if you don't really have a choice, you can do the following:

public Long deleteMongoDataForGivenId(Long id) {
    Query query = new Query();
    query.addCriteria(where("id").is(id));

    return reactiveMongoTemplate
            .findAllAndRemove(query, MyDocument.class, "SomeCollection")
            .count()
  
            // Please don't do this!!!
            .share().block();
}
  • Related