[
https://issues.apache.org/jira/browse/CAMEL-25159?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18121015#comment-18121015
]
Andrea Cosentino commented on CAMEL-25159:
------------------------------------------
PR opened: https://github.com/apache/camel/pull/27116
Both fixes in one PR, a commit each, since they come from the same pass over
the component.
----
_Claude Code on behalf of oscerd (Andrea Cosentino)._
> camel-mongodb - findAll, distinct and aggregate execute their query twice
> -------------------------------------------------------------------------
>
> Key: CAMEL-25159
> URL: https://issues.apache.org/jira/browse/CAMEL-25159
> Project: Camel
> Issue Type: Bug
> Components: camel-mongodb
> Reporter: Andrea Cosentino
> Assignee: Andrea Cosentino
> Priority: Major
>
> h3. Summary
> {{findAll}}, {{distinct}} and {{aggregate}} run their query against MongoDB
> **twice**: once to read the
> results and once more in a {{finally}} block that was meant to close the
> cursor. The cursor that was
> actually read is never closed.
> h3. Details
> All three follow the same shape in {{MongoDbProducer}}:
> {code:java}
> try {
> ret.iterator().forEachRemaining(result::add);
> exchange.getMessage().setHeader(RESULT_PAGE_SIZE, result.size());
> } finally {
> ret.iterator().close();
> }
> {code}
> {{MongoIterable.iterator()}} is not an accessor for an already-open cursor,
> it executes the operation.
> From {{mongodb-driver-sync}} 5.9.2:
> {code:java}
> public MongoCursor<T> iterator() {
> return new MongoBatchCursorAdapter<>(execute());
> }
> {code}
> So the {{finally}} opens a *new* cursor - a second round trip to the server,
> and for {{aggregate}} a
> second execution of the whole pipeline - and closes that one, while the
> cursor drained by
> {{forEachRemaining}} is never closed explicitly. If {{forEachRemaining}}
> throws part way through, that
> first cursor is left open.
> Affected operations: {{findAll}} and {{aggregate}} when the endpoint's
> {{outputType}} is not
> {{MongoIterable}}, and {{distinct}} always.
> h3. Proposed fix
> Hold the cursor in a variable and use try-with-resources, so the cursor that
> is read is the cursor that
> is closed and the query runs once:
> {code:java}
> try (MongoCursor<Document> cursor = ret.iterator()) {
> cursor.forEachRemaining(...);
> ...
> }
> {code}
> ----
> _Reported by Claude Code on behalf of oscerd (Andrea Cosentino)._
--
This message was sent by Atlassian Jira
(v8.20.10#820010)