I am staring this series of blog posts. This will cover few tips and / or tricks from ROR. We as developer come across a situation, where we struggle to solve the problem. Once solved we realise that, in our trial and error efforts we have found some trick, which is not documented.
This blog post is an effort to collect such tips and tricks and make developers life easy !!!
Tip : .first and .last returns same object on mongoid 5
Database : Mongodb
There are 2 ways to overcome this problem.
Simple query that comes in mind is to use “all[-1]”. But this is expensive. Instead use order to get last document. Here is the benchmark of both queries. Collection used for this benchmark has size as 35783 documents.
Benchmark.ms { Unit.all[-1] }
=> 5881.32297800621
Benchmark.ms { Unit.desc(:id).first }
=> 3.993231992353685