首页 > 解决方案 > 未定义的属性: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未定义?

标签: phpmongodbwamp

解决方案


工作 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);

推荐阅读