1

I'm looking for the fastest way to get the last n objects that was inserted to a set (in mongo).

One way to do it is using sort and limit , but sorting a large data set just to get few objects is not the right way.

It would be great if a new object could be inserted at the beginning of the set, and then just by using limit I could get the last objects.

Notice that sometimes those objects are being updated, and maybe expanded, thats why I've picked mongo.

What is the best way to do it? (with MongoDB, or maybe not?)

Guy P
  • 1,395
  • 17
  • 33

1 Answers1

3

The best way is

db.collection.find().sort({_id : -1}).limit(n)

_id has default index on it and you don't need define extra index.

use .explain() to find out about your query

db.collection.find().sort({_id : -1}).limit(n).explain()

If you want to get last 6 documents, above query scan just 6+1 documents for returning your result which is the best performance as possible.

Disposer
  • 6,201
  • 4
  • 31
  • 38