PHP和Mongodb无法建立连接

问题描述 投票:0回答:1

我尝试了以下示例以显示收集计数。 这是我所做的:

<?php
 $connection = new MongoDB\Driver\Manager(Mongo URI);
//echo phpinfo();
$collection = new MongoDB\Collection($connection, "new", "items");
$initialCollectionCount = $collection->count();
echo $initialCollectionCount;
?>

我收到以下错误:

Fatal error: Uncaught Error: Class 'MongoDB\Collection' not found in C:\xampp\htdocs\test\test.php:4 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\test.php on line 4

到目前为止,我所做的是:
1)从Pecl网站下载了最新的MongoDB驱动程序,用于PHP 7.1。
2)将DLL文件添加到ext文件夹并编辑php.ini文件。
3)php和mongo Connection的书面代码。

请建议我要使我的代码运行所需做的事情。 请注意,我已将System变量添加为PHP文件夹。 到目前为止,我还没有做过任何事情。

请建议我走正确的路,以便实现我的代码。

php mongodb php-7.1
1个回答
1
投票

您可以尝试使用扩展的MongoDB\\Driver\\Query类检索数据。

// Manager Class / Connection
$connection = new MongoDB\Driver\Manager(Mongo URI);

// Query Class like this. Add your conditions here if there may be any
$query = new MongoDB\Driver\Query(array('id' => 1));

// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$cursor = $connection->executeQuery('new.items', $query);

// Convert cursor to Array and print result
print_r($cursor->toArray());

然后,您可以计算输出数组的元素。

当您使用最新的PHP MongoDB扩展时,此代码运行良好, MongoDB\\Driver\\Manager是该扩展的主要入口点。

回答您的评论:我没有看到列出所有集合的课程。 或者,尝试使用Mongo client直到获得对MongoDB\\Driver\\Manager更多支持

以下是示例代码,列出了数据库中的所有集合:

<?php

$m = new MongoClient();
$db = $m->selectDB("new");
$collections = $db->listCollections();

foreach ($collections as $collection) {
    echo "amount of documents in $collection: ";
    echo $collection->count(), "\n";
}

?>

MongoClient类是旧版PECL软件包mongo的一部分,但不再是最新的mogodb软件包的一部分。

该软件包已被取代,但仍保留其错误和安全修复程序。

© www.soinside.com 2019 - 2024. All rights reserved.