16

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:

  • MongoDB shell version: 2.4.3

  • Mongoid 2.6.0

Thanks!

cortex
  • 5,036
  • 3
  • 31
  • 41

2 Answers2

34

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.

cortex
  • 5,036
  • 3
  • 31
  • 41
  • 4
    IMPORTANT! Assuming you have 9000 records if you do u = User.all.desc('_id').limit(7000) and then u.delete it would delete the 9000 records! Just happened to me on a production app. Luckily I always do a fresh backup before doing such things. – Pod Jun 04 '15 at 06:34
  • @Pod you should convert to array `to_a` after `limit()` (before destroy), read this https://stackoverflow.com/a/20368143/1297435 – rails_id Sep 07 '17 at 09:23
  • 2
    ...and to get the nth record from last `User.all.desc('_id').offset(n).first` – Ravi Misra Jun 14 '19 at 08:21
  • Note: the "origin" link referenced in this answer is now "Not Found". – Chip Roberson May 09 '20 at 14:48
0

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.