mongodbgroovygstring

Groovy ClassCastException on retieving MongoDB aggregation results


I have a Groovy application that uses MongoDB Java Sync Driver v4.x.x.

I've recently upgraded MongoDB from an old v3.4 to new v5.0.12 which requires the new driver mentioned above.

The issue I'm having is that any results I return from the database using:

AggregateIterable<Document> results = collection.aggregate(aggregationPipeline)

Gives me ClassCastException on trying to cast GStringImpl to String.

I've tried:

def cursor = results.cursor()
def list = results.toList()
def iterator = results.iterator()

All give ClassCastExceptions, leaving me with the AggregateIterable that I can't seem to do anything with.

The old API we used returned a AggregationOutput directly from aggregate(), from which we could get a Iterable like so:

AggregationOutput cursor = collection.aggregate(pipeline)
Iterable<DBObject> dbList = cursor.results()

Can anyone tell me how to get around this issue I'm having with GString casting/Mongo AggregateIterable?


Solution

  • The MongoDB Java Driver 4.x.x, returns a stream as the return value of an aggregate operation, you can accumulate its results into a list, like this:

    List<Document> results = collection.aggregate(aggregationPipeline).into(new ArrayList<>());
    

    Reference Article.