php - 未定义的属性:MongoDB\Driver\Manager::$db
问题描述
我有一个在 Windows 10 上的 WAMP 上运行的本地 MongoDB 数据库。我使用的是 PHP 版本 7.2.10、Apache 2.4.35 和 MongoDB 扩展 1.5.3。我有一个正在测试的非常简单的 Web 应用程序,当我尝试通过 php 脚本将数据发送到我的数据库时,出现以下错误:
PHP Notice: Undefined property: MongoDB\Driver\Manager::$db in
C:\wamp64\www\php\test.php
的相关部分test.php
,有问题的文件,如下所示:
$objectId = new MongoDB\BSON\ObjectId();
$dbhost = "127.0.0.1:27017";
$dbname = "db";
$m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($m);
$db = $m->$dbname;
未定义的属性会导致另一个错误:Fatal error: Uncaught Error: Call to a member function selectCollection() on null
这会导致脚本失败。
是什么导致属性MongoDB\Driver\Manager::$db
未定义?
解决方案
工作 php 代码如下所示。请注意是否存在指向'vendor/autoload.php'的链接:
$DB_CONNECTION_STRING="mongodb://YourCredentials";
require '../../vendor/autoload.php';
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
然后,如果您使用 MongoDB\Driver\Manager,这是 MongoDB 驱动程序的现代版本,您的 CRUD 操作将如下所示:
在集合中创建一个文档:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$doc = ['name' => 'John', age => 33, profession => 'Guess what?'];
$bulkWrite->insert($doc);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
按名称读取集合中的文档,但有限制:
$filter = ['name' => 'John'];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
通过 MongoDb _id读取集合中的文档,但有限制:
$filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
$options = ['limit' => 2];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
更新集合中的文档:(在此处阅读有关选项 upsert 和 multi 的更多信息)
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John'];
$update = ['$set' => ['name' => 'Smith', age: 35, profession => 'Guess what?']];
$options = ['multi' => false, 'upsert' => false];
$bulkWrite->update($filter, $update, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
删除集合中的文档 - 删除:
$bulkWrite = new MongoDB\Driver\BulkWrite;
$filter = ['name' => 'John', age => 35];
$options = ['limit' => 1];
$bulkWrite->delete($filter, $options);
$manager->executeBulkWrite('db.MyCollection', $bulkWrite);
推荐阅读
- quarkus - Quarkus 原生图像大小
- ios - 如何在 Xamarin IO 中每隔一定时间间隔安排一个任务?
- amazon-web-services - 从 S3 存储桶获取数据
- javascript - 如何更改表单的日期输出
- rust - 为什么rust认为借用在其他分支中很活跃
- python - Python中异常处理中的异常
- javascript - 如何从 src 构建图像而不构建 html 并在 js 中导入
- python - 在 Python 中使用 SQLite 传递安全查询参数
- visual-studio-code - VSCode 启动配置无需调试即可运行 python 文件
- oracle - Oracle Apex 更改自动完成输入颜色