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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…