2

如果我在集合 mongo 中的数据是这样的

{ "_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" }

如果我想要第 6 行没有循环数据的数据。php中是否有短代码来获取该行中的数据???

4

2 回答 2

4

为了找到第六条记录,您需要使用一些MongoCursor 方法

  • sort()所以有一个特定的顺序(例如 by _id
  • skip()跳过一些记录(跳过 5 找到第 6 个)
  • limit()限制为一个结果

代码示例:

<?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);
?>

样本输出:

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

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

请注意,skip()如果您需要跳过大量文档,则性能可能会成为问题。如果可能的话,一个性能更高的选项是使用有限制的范围查询。

于 2012-08-20T04:58:24.117 回答
0

这看起来像一个 json 格式的内容,如何将它们全部读入一个对象,然后将它们 json_decode 成另一个对象,以便稍后您可以读取第 6 行。

于 2012-08-20T04:38:11.703 回答