Skip to content

MONGOID-5863 #last overrides #skip #5975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/mongoid/contextual/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1122,7 +1122,7 @@ def retrieve_nth_to_last(n)
end

def retrieve_nth_to_last_with_limit(n, limit)
v = view.sort(inverse_sorting).skip(n).limit(limit || 1)
v = view.sort(inverse_sorting).limit(limit || 1)
v = v.skip(n) if n > 0
raw_docs = v.to_a.reverse
process_raw_docs(raw_docs, limit)
Expand Down
6 changes: 6 additions & 0 deletions spec/mongoid/contextual/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3292,6 +3292,12 @@
it "limits the results" do
expect(context.skip(1).entries).to eq([ new_order ])
end

context "with #last" do
it "returns the nth from last element" do
expect(context.skip(1).last).to eq(depeche_mode)
end
end
Copy link
Contributor

@johnnyshields johnnyshields May 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method has sort(inverse_sorting) and then later v.to_a.reverse, which ensure the ordering in the case that multiple docs are returned.

Is this covered by tests? i.e. ensuring correct document ordering the result for multiple docs?

  • combining skip(n) with limit(m) (where n, m > 1)
  • last(n) (where n > 1)

end

describe "#sort" do
Expand Down
Loading