Adapt Enumerator / Iteratee to Stream
I have a Spray application where I'm using reactive-mongo to connect to my Mongo database.
val collection: BSONCollection = db("ping") val cursor: Cursor[Ping] = collection.find(BSONDocument()).cursor[Ping] val e: Enumerator[Ping] = cursor.enumerate()
ReactiveMongo's cursor allows me to get the data by chunks. This cursor can be transformed to a play.api.libs.iteratee.Enumerator which is in turn connected to a play.api.libs.iteratee.Iteratee where any code I want is called for each element of the collection. "Ping" is my domain entity.
With Spray it's possible to return a Stream[Ping] that will be marshalled into a JSON response. I'd like to know if it's possible to adapt the Enumerator or the Iteratee to a Stream, so I can return that.
You can use collect[Stream] instead of enumerate on the Cursor instance to do that:
val collection: BSONCollection = db("ping") val cursor: Cursor[Ping] = collection.find(BSONDocument()).cursor[Ping] val stream: Stream[Ping] = cursor.toList.toStream
EDIT: Used cursor.toList.toStream. This will gather all the documents matched by the query, then produce a stream.