Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

php mongodb find nth entry in collection

I am trying to retrieve the nth entry in my collection.
This seems to work using find() but i would think there is a cleaner solution using findOne() and maybe sort()?
can anyone help out 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's the 3rd entry id
    $i++;
}

The solution provided here is not applicable to my problem, which is why I'm asking this question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Skip() does not use an index effectively so putting a index on any field within the collection would be pointless.

Since you wish to skip() nth documents, if the value of skip() is low (depends on your system but normally under 100K rows on a full collection scan) then it might be OK. The problem is that normally it is not. Mongo, even with an index, will be required to scan the entire result set before being able to skip over it which will induce a full collection scan no matter what in your query.

If you were to do this often and in random ways it might be better to use an incrementing ID combineing another collection with findAndModify to produce an accurate document number ( http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field ).

This however induces problems, you must mantain this ID especially when deletes occur. One method around this is to mark documents as deleted instead of actually deleting them. When you query for the exact document you omit deletes and limit() by one allowing you to get the next closest document to that position like so:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...