cortex
cortex

Reputation: 5226

How to get last N documents with mongoid?

I have found some information to accomplish this in mongoDB, but I need it with mongoid. So I can do something like:

User.last(7000).each do ....

I'm using:

Thanks!

Upvotes: 18

Views: 8558

Answers (2)

Puttaraj Koliwad
Puttaraj Koliwad

Reputation: 1

Aggregations can directly be chained to a Model in rails irrespective of the ORM used. We don't need to use all. You could just do the following

User.limit(3000).desc('_id')

This will only return the Mongoid criteria. To see the data you can chain .all to the criteria. You can directly do operations on the criteria also, without having to chain .all or to_a.

Upvotes: 0

cortex
cortex

Reputation: 5226

Now I found a solution from mongoid origin:

User.all.desc('_id').limit(7000)

It sorts the users in descending order according to the id.

Upvotes: 35

Related Questions