1

我尝试使用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 ( ) 

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

4

3 回答 3

0

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

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

然后我们在这种情况下按名称检索数据,限制为2 个文档,并且只想获取字段 nameageaddress等。投影选项可用于指定应返回哪些字段,使用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);

如果我们需要获取所有列,那么我们只需完全省略投影选项,如下所示:

  $filter = ['name' => 'daniel'];
  $options = [];
  $query = new MongoDB\Driver\Query($filter, $options);
  $manager->executeQuery('db.MyCollection', $query);
于 2018-11-23T01:33:40.960 回答
-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
}
于 2013-07-20T11:26:15.707 回答
-2

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

foreach($cursor as $document) {  
 var_dump($document);  
}
于 2013-07-15T11:24:27.230 回答