【发布时间】:2015-02-02 08:43:39
【问题描述】:
我正在尝试使用 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 循环之外我在打印其余字段时遇到了问题。
【问题讨论】: