在PHP中检索Mongo集合的字段

时间:2013-07-15 09:46:22

标签: php mongodb-php

我尝试在光标上使用fields()方法:

<?php
$mongo  = new Mongo("mongodb://localhost");
print_r($mongo);

$db = $mongo->test;

// access collection
$collection = $db->test;

// execute query
// retrieve all documents
print_r($test);

$cursor = $collection->find();
print_r($cursor);

$fields = $cursor->fields(array("summary" => true));
print_r($fields);

输出结果为:

Mongo Object ( [connected] => 1 [status] => [server:protected] => [persistent:protected] => )
MongoCursor Object ( )
MongoCursor Object ( ) 

看起来驱动程序和连接工作但我无法检索字段的不同摘要。

3 个答案:

答案 0 :(得分:0)

假设我们可以访问名称为 db 的mongodb数据库,并将从 MyCollection 检索数据并使用 MongoDB \ Driver \ Manager

  $manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );

然后,在这种情况下,我们通过 name 并限制了 2 个文档来检索数据,并希望仅获取仅字段 名称年龄地址等等。 投影选项可用于指定应返回哪些字段,并使用 0 排除并使用 1 包括:

  $filter = ['name' => 'John'];
  $options = [ 'projection' => ['_id' => 0, 'name' => 1, 'age' => 1, 'address' => 1], 'limit' => 2 ];
  $query = new MongoDB\Driver\Query($filter, $options);
  $manager->executeQuery('db.MyCollection', $query);

如果需要获取所有列,则只需完全省略 projection 选项,如下所示:

  $filter = ['name' => 'daniel'];
  $options = [];
  $query = new MongoDB\Driver\Query($filter, $options);
  $manager->executeQuery('db.MyCollection', $query);

答案 1 :(得分:-1)

 const HOST = 'localhost';
 const PORT = 27017;
 const DBNAME = 'test';
 const COLLECTION = 'test';
 $connectionString = sprintf('mongodb://%s:%d', HOST, PORT);

 try {

        $connection = new Mongo($connectionString);
        $database = $connection->selectDB(DBNAME);

 } catch (MongoConnectionException $e) {

        throw $e;

}
$collection = $database->selectCollection(COLLECTION);

try{
        $query = array();
        $specifyKey = array("summary" => true);
        $cursor = $collection->find($query , $specifyKey);

}catch(MongoException $e) {

        die('Failed to find One data '.$e->getMessage());

}catch (MongoCursorException $e) {

    echo "error message: ".$e->getMessage()."\n";
    echo "error code: ".$e->getCode()."\n";
}

while ($cursor->hasNext()){

    $nextCursor = $cursor->getNext(); 
    //process next cursor
}

答案 2 :(得分:-2)

在$ cursor变量之后尝试使用foreach。它遍历游标结果。

foreach($cursor as $document) {  
 var_dump($document);  
}