我尝试在光标上使用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 ( )
看起来驱动程序和连接正常,但我无法检索字段的不同摘要。
假设我们可以访问名为db的mongodb数据库,将从MyCollection检索数据,并使用mongodb ''Driver''Manager:
$manager = new MongoDB'Driver'Manager( $DB_CONNECTION_STRING );
然后,在这种情况下,我们通过name检索数据,并限制2文档,并希望获得仅字段name、age和address等投影选项可用于指定应使用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);
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
}
在$cursor变量之后,尝试foreach。它遍历光标结果。
foreach($cursor as $document) {
var_dump($document);
}