Reputation: 414
I'm working with MongoDB and I want to display last 10 entries in collection, which should be ordered by score. The problem is that there is about 2 million entries so each query takes up from 5-7 sec.
Things were working pretty good when the database was smaller but with increasing size problems occurred. I checked .explain('executionStats')
and I noticed that in result there is nReturened: 10
and totalDocsExamined: 1959933
which means that it is going through whole database to return last 10 entries. (also totalKeysExamined: 0
if someone needs that info)
Searching query looks like this:
db.logs.find({}).sort({"score":-1}).limit(10).toArray()
Stages of query are COLLSCAN, SORT_KEY_GENERATOR, SORT
I'm aware that find({})
is going through whole DB, then sorting it, and getting last 10 results. But what should be the better way to speed the things up?
Upvotes: 1
Views: 1284
Reputation: 1922
Create an index on {score: 1}
will help greatly. Mongo definitely uses index for sorting if available. You should see IXSCAN, FETCH, and LIMIT stages after creating the index.
Upvotes: 3
Reputation: 66
You need to create index on key you are performing search in mongodb. Indexing will help you to retrieve data faster.
Use: db.collection.createIndex(keys, options)
For more information please read the doc MongoDB create index
Hope this will help. Good luck!
Upvotes: 1