用PHP连接我的mongo(过滤返回的文件)

时间:2015-02-02 08:43:39

标签: php mongodb

我正在尝试使用php代码连接到我的mongo数据库。我对已经尝试过的东西不太确定。这是我的代码:

$mongoHostname = ".. . ... . ... . ...";//"localhost";
$databaseName = "db";

$conn = new Mongo('mongodb://'.$mongoHostname.'/'.$databaseName);
// access database
$db = $conn->$databaseName;
// access collection
$collection = $db->coll;

$file = 'names.txt'; //a file with screenames
$data = file($file) or die('Could not read file!');

foreach ($data as $line)
{
  $cursor = $collection->find(array('user.screen_name' => $line));
  print_r($cursor);

}

我在mongo中的集合coll有一个字段用户,其中包含一些关于用户的元素,其中一个是screen_name。如何显示查询对象?我连接正确的mongo数据库吗?我怎么检查呢?我已经安装了php驱动程序。上面的代码没有回应。

编辑:基本上我发现我必须使用以下命令ini_set('mongo.long_as_object', 1);我不知道这个命令的确切含义。最后,我设法返回包含所有用户数据的游标对象。如何过滤该文档以提取特定字段,例如user.description和user.location?我试着这样做:

foreach ($data as $line)
{
 $line = preg_replace('/\s+/', '', $line);
 $cursor = $collection->find(array('user.screen_name' => $line));

 while ($cursor->hasNext()){

    $nextCursor = $cursor->getNext(); 
    $text = (string)$nextCursor["text"];
    echo $text. '<br>';
    //process next cursor
 }

    $descr = (string)$cursor["user"]['description'];
    $location = (string)$cursor["user"]['location'];
    $url = (string)$cursor["user"]['url'];
    $image_url = (string)$cursor["user"]['profile_image_url'];

    echo "user information:   ".$descr.'<br>';
    echo 'user location:    '.$location.'<br>';
    echo "url: ".$url."<br>";
         echo  "<a href=\"" . $temp . "\" style=\"text-decoration:none;\">" . $temp . "</a><br>\n";
 echo "<br><br>";
 }

虽然第一个while循环可以正常打印文档文本,但在while循环之外我打印休息字段时出现问题。

2 个答案:

答案 0 :(得分:1)

如何过滤特定字段:

$fields = array('user.description'=>true);
$cursor = $collection->find(array('user.screen_name' => $line),$fields);

将结果用作数组:

$array = iterator_to_array($cursor);

请阅读官方文件: http://php.net/manual/en/mongocollection.find.php

答案 1 :(得分:0)

最后,我所做的是迭代每个文档而不是所有文档。我的代码:

$temp_url = "https://twitter.com/";
foreach ($data as $line)
{

 $line = preg_replace('/\s+/', '', $line);
 $cursor = $collection->find(array('user.screen_name' => $line));

 while ($cursor->hasNext()){

    $nextCursor = $cursor->getNext(); 
    $text = (string)$nextCursor["text"];
    echo $text. '<br>';

    $img = $nextCursor["images"];
    foreach ($img as $image) {
        print_r($image['link']);
        echo "<img src='" . $image['link'] . "' alt='error'>";
        echo '<br>';
    }

    //process next cursor
      foreach($cursor as $document) {  
         echo ($document['user']['description'].'<br>');
         echo ($document['user']['location'].'<br>');
         echo ($document['user']['url'].'<br>');
    }  
 }