Search code examples
mongodbiterationmorphianosql

Morphia/MongoDB: how to iterate over distinct fields


I'd like to iterate over a list of distinct fields in a given document. Using the MongoDB command line, I can kind of get what I want by doing something like:

db.MyDoc.distinct("someField")

... except that it returns all the results as a giant BSON.

Is there a way to do this in Morphia, and to furthermore return it as an Iterable, so that all the results are not read into memory all at once?

I imagine that distinct() is implemented as some kind of in-memory hashmap, which probably means that there's no point in my trying to iterate over the results piecemeal to avoid having them all in memory at once.


Solution

  • Even when this is supported by morphia the result of distinct is still a single (bson) document, with an array of distinct values for the result field. It will have to be read completely into memory, basically.