Skip to content

MONGOID-6053 Respect the limit in HasMany::Enumerable#first and #last - #6208

Open
hfvmarques wants to merge 1 commit into
mongodb:masterfrom
hfvmarques:MONGOID-6053-enumerable-limit
Open

hfvmarques wants to merge 1 commit into
mongodb:masterfrom
hfvmarques:MONGOID-6053-enumerable-limit

Conversation

@hfvmarques

Copy link
Copy Markdown

first(limit) and last(limit) on a has_many association returned a single document once the association was loaded, or when it had added documents, because the limit was only passed to the unloaded criteria. The same call returned an array of up to limit documents when the association was not loaded, so the result depended on whether something had loaded the association before.

Handle a given limit separately: use the loaded documents when the association is loaded, or query only limit documents when it is not, then merge the added documents by _id, preferring the in-memory instance and keeping new documents last, as #each does. With a limit, both methods now always return an array. Calls without a limit are unchanged.

MONGOID-6053

Please backport it to 9.0-stable

first(limit) and last(limit) on a has_many association returned a single
document once the association was loaded, or when it had added
documents, because the limit was only passed to the unloaded criteria.
The same call returned an array of up to limit documents when the
association was not loaded, so the result depended on whether something
had loaded the association before.

Handle a given limit separately: use the loaded documents when the
association is loaded, or query only limit documents when it is not,
then merge the added documents by _id, preferring the in-memory
instance and keeping new documents last, as #each does. With a limit,
both methods now always return an array. Calls without a limit are
unchanged.
@hfvmarques
hfvmarques requested a review from a team as a code owner November 11, 2026 17:58

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant