Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nth item from a collection

Tags:

mongodb

I'm in the learning phase of mongodb.

I have a test website project where each step of a story is a domain.com/step for instance, step 14 is accessed through domain.com/14

In other words, for the above case, I will need to access 14th document in my collection to serve it.

I've been using find().skip(n).limit(1) method for this so far to return nth document however it becomes extremely slow when there are too many documents to skip. So I need a more efficient way to get the nth document in my collection.

Any ideas are appreciated.

like image 867
Mia Avatar asked Aug 08 '15 18:08

Mia


1 Answers

Add a field to your documents which tells you which step it is, add an index to that field and query by it.

Document:

{
     step:14
     text:"text",
     date:date,
     imageurl:"imageurl"
}

Index:

db.collection.createIndex({step:1});

Query:

db.collection.find({step:14});

Relying on natural order in the collection is not just slow (as you found out), it is also unreliable. When you start a new collection and insert a bunch of documents, you will usually find them in the order you inserted them. But when you change documents after they were inserted, it can happen that the order gets messed up in unpredictable ways. So never rely on insertion order being consistent.

Exception: Capped Collections guarantee that insertion order stays consistent. But there are very few use-cases where these are useful, and I don't think you have such a case here.

like image 121
Philipp Avatar answered Sep 30 '22 18:09

Philipp