How Mongo.Stream works and how to use it
masterMost query functions return a %Mongo.Stream{} struct, which implements the Enumerable protocol. The driver uses this to manage MongoDB sessions automatically: it checks out a session, streams batches from the server, and checks the session back in once the stream is exhausted.
Warning: Do not attempt to access the internal :docs field of the %Mongo.Stream{} struct directly. Doing so will prevent the session from being checked back in and will only retrieve the first batch of documents.
Correct Usage: Always process the result using an Enum or Stream function to ensure proper session lifecycle management.
# CORRECT: Use Enum to ensure session management
@topology
|> Mongo.aggregate(collection, pipeline, opts)
|> Enum.to_list()
# INCORRECT: Accessing internal docs directly leaves session open
%Mongo.Stream{docs: docs} = Mongo.aggregate(@topology, collection, pipeline, opts)
Enum.map(docs, fn elem -> elem end)