I encountered a bug of mongoid, which return first document when I invoking the method last
class Post
include Mongoid::Document
end
Post.create
Post.create
Post.first == Post.last #=> true
The versions info:
- mongoid: "5.0.2"
- mongodb: v3.2.1
- Rails 4.2.5
That's not a bug in Mongoid, that's a bug in your expectations of the
first
andlast
methods. From the fine version 5 manual:So
first
(as of Mongoid5) gives you the first document in the query with respect to the current order but it no longer supplies a default order. You'll need to supply your ownsort
order in the query if you wantfirst
to behave like it used to.Similarly for
last
.It seems the old behaviour is back in Mongoid 6? - I'm using 6.1.0 and I'm experiencing the following:
So using .first instead of .limit(1).entries.first is about twice as slow. One workaround is to do: .first(id_sort: :none)
hope that helps :)