Count Aggregate with empty Match results in NPE

Hi Folks,

I am counting documents returned by a match.

public Long datasetSize(String setId) {
    return mongoClient
                            match(Filters.eq("datasetId", datasetId)),

This works if the match clause matches one or more documents. But if the match clause matches no documents, the result of first() is null and the invocation of getInteger() fails with a NullPointerException.

I was expecting that the count() aggregate would yield an Integer.ZERO result if the match was empty.

I have tested this with:


Any suggestions?

If the null result from first() is indeed expected, is there a better way to express a default result than wrapping the whole pipeline in try / catch and returning 0 in case of NullPointerException? My concern is that an NPE might occur for at various places and for various reasons, and only the first() == null case should give rise to a 0 return.

Kind regards, Robin.

Essentially, the point is not to try to interpret count in the pipeline, instead, return a document containing count in a field and test it for null in plain Java outside the pipeline.