0

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?

ionised
  • 123
  • 1
  • 12

1 Answers1

1

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.

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
  • 1
    I actually had two separate problems, one of which your answer fixed! The other was an issue with the MongoDB plugin for Grails, which assumes the use of GORM (entity mapping) which this application only does with MySQL tables, not MongoDB collections. For that reason I've opted to just use the low-level MongoDB Java Sync driver API rather than whatever magic the Grails MongoDB plugin is trying to do with mapping. – ionised Feb 23 '23 at 06:51