切片数组并仅获取切片数组

时间:2015-04-15 16:53:14

标签: php mongodb

在MongoDB中,我想分页一个数组。所以我这样做:

$foo = $coll->findOne(
    $idQuery,
    [$key => ['$slice' => [$page * $limit, $limit]]]
);

返回整个文档,并将$key数组切成薄片。我如何告诉MongoDB只获取切片数组$key?就像您在投影中设置[$key => 1]一样,并且您只获得$key

1 个答案:

答案 0 :(得分:0)

使用新的MongoDB PHP驱动程序,我们可以通过以下方式完成:

<?php

try {

    $filter = [];
    $options = ["limit" => 5, "skip" => 2];

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query($filter, $options);     

    $rows = $mng->executeQuery("testdb.cars", $query);

    foreach ($rows as $row) {

           print_r($row);
    }    


} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";    
}

?>

该示例跳过前两行并将输出限制为五行。 选项参数中有limitskip个值 MongoDB\Driver\Query做这项工作。