如何从mongoDB集合中的特定行(例如,第6行)获取数据?

If my data in collection mongo is something like this

{ "_id" : ObjectId("4fff9946af8c6149aed251ab"), "subject_slug" : "math", "lesson_slug" : "mat01" }
{ "_id" : ObjectId("4fff9946af8c6149aed251ac"), "subject_slug" : "math", "lesson_slug" : "mat02" }
{ "_id" : ObjectId("4fff9946af8c6149aed251ad"), "subject_slug" : "math", "lesson_slug" : "mat03" }
{ "_id" : ObjectId("4fff9946af8c6149aed251ae"), "subject_slug" : "eng", "lesson_slug" : "eng01" }
{ "_id" : ObjectId("4fff9946af8c6149aed251af"), "subject_slug" : "eng", "lesson_slug" : "eng02" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b0"), "subject_slug" : "eng", "lesson_slug" : "eng03" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b1"), "subject_slug" : "phy", "lesson_slug" : "phy01" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b2"), "subject_slug" : "phy", "lesson_slug" : "phy02" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b3"), "subject_slug" : "phy", "lesson_slug" : "phy03" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b4"), "subject_slug" : "chem", "lesson_slug" : "che01" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b5"), "subject_slug" : "chem", "lesson_slug" : "che02" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b6"), "subject_slug" : "chem", "lesson_slug" : "che03" }
{ "_id" : ObjectId("4fff9946af8c6149aed251b7"), "subject_slug" : "chem", "lesson_slug" : "che04" }

and If I want data in row 6 without loop data. Is there short code in php to get data in that row ???

In order to find the sixth record, you need to make use of some MongoCursor methods:

  • sort() so there is a specific order (eg. by _id)
  • skip() to skip a number of records (skip 5 to find the 6th)
  • limit() to limit to one result

Code example:

<?php
    $mongo = new Mongo();
    $collection = $mongo->mydb->subject;

    $query = array();
    $sort  = array('_id' => 1);

    // Find the 6th record
    $doc = $collection->find($query)->sort($sort)->skip(5)->limit(1)->getNext();

    print_r($doc);
?>

Sample output:

Array
(
    [_id] => MongoId Object
        (
            [$id] => 4fff9946af8c6149aed251b0
        )

    [subject_slug] => eng
    [lesson_slug] => eng03
)

Note that the performance of skip() may be an issue if you need to skip over a large number of documents. A more performant option, if possible, would be to use range queries with a limit.

That looks like a json formatted content, what about reading them all into an object then json_decode them into another so that later you can just read the 6th row out.