Search code examples
javamongodbspring-bootjava-11reactive-mongo-java

How count a mongodb collection with ReactiveMongoTemplate without any query filter?


I would like to determine mongodb collection size in my java spring application. I know that reactive rective Mongo Template has a count() method what does that, however it needs a query param.

So my solution is:

public Mono<Long> collectionSize(){
    Criteria criteria = Criteria.where("_id").exists(true);
    return this.reactiveMongoTemplate.count(Query.query(criteria),MY_COLLECTION_NAME);
}

However I dont like this solution, because I have to use a captain obvious criteria.

Is there any better solution for this problem?

Thanks!


Solution

  • Criteria has an empty constructor.

    public Mono<Long> collectionSize(){
        Criteria criteria = new Criteria();
        return this.reactiveMongoTemplate.count(Query.query(criteria),MY_COLLECTION_NAME);
    }
    

    Reference

    And all of the variants of count requires a query param as documented here

    Query doesn't need criteria, you can just supply the query param. Reference

    public Mono<Long> collectionSize(){
            return this.reactiveMongoTemplate.count(new Query(),MY_COLLECTION_NAME);
        }