我一直在尝试在运行 apache2 的 AWS EC2 linux 实例上使用 PHP 版本 7 连接到我的 MongoDB atlas 集群,以在该数据库/集合中插入和更新值。
我已经安装了 MongoDB 驱动程序版本 4 和 MongoDB PHP 库 1.5.5,在 MongoDB 集群和 AWS 实例上将我的 IP 白名单设置为 0.0.0.0。我也一直在阅读几乎所有关于 stackoverflow 的帖子,这些帖子与其他人在 ec2 实例中连接 MongoDB 和 PHP 的问题有关,并且尝试了很多没有成功的建议。我猜它与可能安装的地方有关,但我不知道为什么我无法连接:/
我使用 Composer 自动加载库,MongoDB.so 文件在正确的位置,我可以在命令行中启动服务。
我的文档根目录设置为我的代码所在的/var/www/IOT/public,并且一直在尝试将所有配置文件保存到/usr/lib64 或/etc/bin
我的集群是IOT,数据库是JT,集合是IOT
require_once '/var/www/html/vendor/autoload.php';
$connection = new MongoDB\Driver\Manager('mongodb+srv://${user}:${pwd}@iot-sjtus.mongodb.net/JT?retryWrites=true&w=majority');
$db = $connection->JT;
$collection = $db->IOT;
$document = array(
"title" => "MongoDB",
"description" => "database",
"likes" => 100,
"url" => "http://www.tutorialspoint.com/mongodb/",
"by" => "tutorials point"
);
$collection->insert($document);
echo "Document inserted successfully";
I expected my collection to be updated with the $document but I get the errors
Notice: Undefined property: MongoDB\Driver\Manager::$JT in /var/www/IOT/public/test.php on line 26
Notice: Trying to get property of non-object in /var/www/IOT/public/test.php on line 28
Fatal error: Uncaught Error: Call to a member function insert() on null in /var/www/IOT/public/test.php:39 Stack trace: #0 {main} thrown in /var/www/IOT/public/test.php on line 39
最佳答案
看来你的连接有误,我的意思是你没有连接到 MongoDB
首先 try catch 异常以了解根本原因:
try {
$connection = new MongoDB\Driver\Manager('mongodb+srv://${user}:${pwd}@iot-sjtus.mongodb.net/JT?retryWrites=true&w=majority');
$db = $connection->JT;
$collection = $db->IOT;
var_dump($collection);
} catch(\Exception $e) {
echo $e->getMessage(), "\n";
}
关于与 MongoDB 的 PHP 连接无法正常工作并响应 "trying to get property of non value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709934/