Php mongodb find the nth item in the collection

I am trying to get the nth record in my collection.
This seems to work using find() , but I think there is a cleaner solution using findOne() and possibly sort() ?
who can help with a better way of writing this please

 $mongo = new Mongo(); $db = $mongo->mydb; $collection = $db->user; $cursor = $collection->find(); $i=0; foreach ($cursor as $obj){ if ($i==3) echo $obj["_id"];//echo the 3rd entry id $i++; } 

The solution given here is not applicable to my problem, so I ask this question.

+2
php mongodb
source share
2 answers

Use skip of (n-1), from your code above:

 $cursor = $collection->find(); $cursor->skip(3); $cursor->next(); $doc = $cursor->current(); 

But I think the best way is to save the counter in the document, which you can use as an index.

+2
source share

Skip () does not use the index efficiently, so placing an index in any field in the collection will be pointless.

Since you want the skip() nth documents, if the skip() value is low (it depends on your system, but usually under 100K lines with a full scan of the collection), then it might be OK. The problem is that this is usually not the case. Mongo, even with an index, will need to scan the entire result set before it can skip it, which will cause a full collection scan, regardless of what is in your query.

If you did this often and randomly, it would be better to use an incremental identifier combining another collection with findAndModify to get the exact document number ( http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto + Incrementing + Field ).

This, however, causes problems; you should use this identifier, especially when deleted. One method is to mark documents as deleted, rather than actually deleting them. When you request the exact document, you omit the deletion and limit() by one so that you can get the next nearest document to this position as follows:

 $cur = $db->collection->find(array('ai_id' => array('$gt' => 403454), 'deleted' => 0))->limit(1); $cursor->next(); $doc = $cursor->current(); 
+4
source share

All Articles